Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
Hi AllI am trying to write a query where it will return the subtotals for each product based on company. This is what the table looks likeCo Product1 Product2ABC 1 0ABC 1 1XYZ 0 0XYZ 1 0This is what i am trying to achieveCo Product1 Product2ABC 2 1XYZ 1 0Thank you in advance
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2006-06-02 : 00:14:06
[code]select Co, sum(Product1), sum(Product2)from yourtablegroup by Co[/code]KH
caconsul
Starting Member
3 Posts
Posted - 2006-06-02 : 00:19:49
Thank you but that query returns the totals asABC 2 2XYZ 1 1 which is not correct
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2006-06-02 : 00:24:00
No. It is correct as what you wanted.
declare @table table( Co varchar(10), Product1 int, Product2 int)insert into @tableselect 'ABC', 1, 0 union allselect 'ABC', 1, 1 union allselect 'XYZ', 0, 0 union allselect 'XYZ', 1, 0select Co, sum(Product1) as Product1, sum(Product2) as Product2from @tablegroup by CoCo Product1 Product2 ---------- ----------- ----------- ABC 2 1XYZ 1 0(2 row(s) affected)
KH
caconsul
Starting Member
3 Posts
Posted - 2006-06-02 : 00:30:45
Thank you that worked. How would you change the query if you also want to know the count of each product by company ?
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2006-06-02 : 00:33:20
add the product to the group byGROUP BY CO, PRODUCTKH