Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can this be done? 1

Status
Not open for further replies.

Laeg

Programmer
Nov 29, 2004
95
0
0
IE
I have a table of CartItems, with the ProductID bought and then an Extra field which is true or false. I want to see a grouping of a count of each ProductID but within that count I want to know the count of ProductIDs with extras.

So given

Code:
create table test(CartItemID int, ProductID int, Extra int);

insert into test (CartItemID, ProductID, Extra) values (100, 1, 1);
insert into test (CartItemID, ProductID, Extra) values (200, 2, 0);
insert into test (CartItemID, ProductID, Extra) values (300, 2, 0);
insert into test (CartItemID, ProductID, Extra) values (400, 1, 1);

select ProductID, count(ProductID) as Total
from test
group by ProductID;

produces...

ProductID | Total
1 2
2 2

I'd like it to say ...

ProductID | Total | ExtraCount
1 2 2 <-- True As 2 instances of a ProductID 1 purchase also had Extra (CartItemID 100, 400)
2 2 0 <-- False As 0 instances of a ProductID 2 purchase had Extra

Can this be done?

Thanks for replies
 
Code:
SELECT ProductID 
     , COUNT(*) AS Total 
     , COUNT(CASE WHEN Extra = 1
                  THEN 'Science!!'
                  ELSE NULL END) AS ExtraCount
  FROM CartItems
GROUP
    BY ProductID
:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Cheers! Now if only you could translate that into .NET Linq it'd make my day week!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top