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 2000 Forums
 Transact-SQL (2000)
 Subtotals for each product

Author  Topic 

caconsul
Starting Member

3 Posts

Posted - 2006-06-02 : 00:11:52
Hi All

I am trying to write a query where it will return the subtotals for each product based on company. This is what the table looks like

Co Product1 Product2
ABC 1 0
ABC 1 1
XYZ 0 0
XYZ 1 0

This is what i am trying to achieve

Co Product1 Product2
ABC 2 1
XYZ 1 0

Thank 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 yourtable
group by Co[/code]


KH

Go to Top of Page

caconsul
Starting Member

3 Posts

Posted - 2006-06-02 : 00:19:49
Thank you but that query returns the totals as

ABC 2 2
XYZ 1 1

which is not correct
Go to Top of Page

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 @table
select 'ABC', 1, 0 union all
select 'ABC', 1, 1 union all
select 'XYZ', 0, 0 union all
select 'XYZ', 1, 0

select Co, sum(Product1) as Product1, sum(Product2) as Product2
from @table
group by Co

Co Product1 Product2
---------- ----------- -----------
ABC 2 1
XYZ 1 0

(2 row(s) affected)



KH

Go to Top of Page

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 ?

Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2006-06-02 : 00:33:20
add the product to the group by

GROUP BY CO, PRODUCT


KH

Go to Top of Page
   

- Advertisement -