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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Help!! Question about summing query

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_nbr
DEPT table columns: dept_nbr, dept_desc
SUB_CAT table columns: sub_cat_nbr, sub_cat_desc

Would this work?

SELECT distinct
dept.dept_desc,
sub_cat.sub_cat_desc,
SUM(sales.sales$)
FROM
dept, sub_cat, item, sales
WHERE
dept.dept_nbr = item.dept_nbr
AND sub_cat.sub_cat_nbr = item.sub_cat_nbr
AND 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 TotalSales
from SALES as s
join ITEM as i on i.item_nbr=s.item_nbr
join DEPT as d on d.dept_nbr=i.dept_nbr
join SUB_CAT as sc on sc.sub_cat_nbr=i.sub_cat_nbr
group 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.
Go to Top of Page

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.
Go to Top of Page

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 TotalSales
from SALES as s
join ITEM as i on i.item_nbr=s.item_nbr
join DEPT as d on d.dept_nbr=i.dept_nbr
join SUB_CAT as sc on sc.sub_cat_nbr=i.sub_cat_nbr
group 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.
Go to Top of Page
   

- Advertisement -