Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
pinecrest515
Starting Member
11 Posts |
Posted - 2011-01-26 : 11:24:35
|
I have a question about aggregating numbers. Suppose I have a SALES table that whose records are at an item transaction level (i.e. it displays sales by item). I also have an ITEM table that contains item dept_nbr and sub_cat_nbr.There is a DEPT table that maps dept_nbr to dept_desc, and a SUB_CAT table that maps sub_cat_nbr to sub_cat_desc.Question: Suppose I want to find the total sales listed by department and subcategory descriptions. How can I best write the SQL? I don't want to see sales at the item level, only on the department and subcategory levels.SALES table columns: item_nbr, sales$ITEM table columns: item_nbr, dept_nbr, sub_cat_nbrDEPT table columns: dept_nbr, dept_descSUB_CAT table columns: sub_cat_nbr, sub_cat_descWould this work?SELECT distinctdept.dept_desc,sub_cat.sub_cat_desc,SUM(sales.sales$)FROMdept, sub_cat, item, salesWHEREdept.dept_nbr = item.dept_nbrAND sub_cat.sub_cat_nbr = item.sub_cat_nbrAND item.item_nbr = sales.item_nbr |
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2011-01-26 : 11:36:46
|
select d.dept_desc,sc.sub_cat_desc,s.item_nbr, sum(s.sales) as TotalSalesfrom SALES as sjoin ITEM as i on i.item_nbr=s.item_nbrjoin DEPT as d on d.dept_nbr=i.dept_nbrjoin SUB_CAT as sc on sc.sub_cat_nbr=i.sub_cat_nbrgroup by d.dept_desc,sc.sub_cat_desc,s.item No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
pinecrest515
Starting Member
11 Posts |
Posted - 2011-01-26 : 11:52:41
|
But this will give sales at item level, with dept and sub_cat desc repeated, right? I would like to find total sales at dept and sub_cat levels. |
 |
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2011-01-26 : 11:56:44
|
I missed that point.Try this:quote: Originally posted by webfred select d.dept_desc,sc.sub_cat_desc, sum(s.sales) as TotalSalesfrom SALES as sjoin ITEM as i on i.item_nbr=s.item_nbrjoin DEPT as d on d.dept_nbr=i.dept_nbrjoin SUB_CAT as sc on sc.sub_cat_nbr=i.sub_cat_nbrgroup by d.dept_desc,sc.sub_cat_desc No, you're never too old to Yak'n'Roll if you're too young to die.
No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
|
|
|
|
|