Question

I have limited experience with SQL and I am currently working on a small project to create a view from different tables. However I keep getting a cartesian product in the result.

I have 3 tables that I am working with, first table has information on each branch, second table has account numbers and names and the third table has monthly totals. I want to create a view where each row has the account numbers followed by a column for each month.

ACCT Table - Number (Primary Key), Acct Number, Account Name and bunch of other columns that are not important for this project.

TOTAL Table - Branch Number (points to BRANCH table), Month (MM-YYYY format), Acct Number (Points to the primary key of the ACCT table) and the monthly totals column.

Acct - Acct Name - Jan Amount - Feb Amount - Mar Amount .....Dec Amount

I wanted to do something like a for-each loop (for each acct, show the monthly totals) but since SQL doesn't have that option I did the following. I am not even joining the branch table at this point and with only 2 months selected I am getting a cartesian product.

select a.scode glacct, a.sdesc glacctdescp,
t1.smtd Amt01, t2.smtd Amt02
from acct a
inner join total t1 on a.hmy = t1.hacct and t1.umonth = '2013-01-01' and t1.ibook = '1'
left outer join total t2 on a.hmy = t2.hacct and t2.umonth = '2013-02-01' and t2.ibook = '1'

I would appreciate it if you can tell me how to fix the inner join statements since that is where I have the problem. Individually it gives me the information I am looking for but joins are not working.

Thanks

Was it helpful?

Solution

in mysql, if you want total by month, this should look like that

select a.scode glacct, a.sdesc glacctdescp
sum(case when month(t.umonth) = 1 then t.smtd else 0 end) as JanuaryAmount,
sum(case when month(t.umonth) = 2 then t.smtd else 0 end)as FebruaryAmount,
sum(case when month(t.umonth) = 3 then t.smtd else 0 end) as MarchAmount
--etc.
from acct a
inner join total t on a.hmy = t.hacct
where year(t.umonth)=2013
and t.ibook = 1
group by a.scode, a.sdesc

OTHER TIPS

The answer from Raphael is probably pretty close, The big reason for your Cartesian product is that you are not grouping and summing the detail lines, which I think is your goal. Another way to approach it would be to simply group by the Year, Month and Account so you would get a result line for each account each month of each year in the data set.

select a.scode glacct, a.sdesc glacctdescp,
sum(t1.smtd)
from acct a
inner join total t1 on a.hmy = t1.hacct and t1.umonth = '2013-01-01' and t1.ibook = '1'
left outer join total t2 on a.hmy = t2.hacct and t2.umonth = '2013-02-01' and t2.ibook = '1'
Group by Year(t1.umonth), Month(t1.umonth),glacct,a.scode
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top