I have a customer table and an orderdetail table
the customer id is a foriegn key in the orderdetail table (I’m simplifying here)
The orderdetail table contains the following columns
OrderId
ItemId
CustomerId
Size
The Size column can take on any one of the following values
1. lr
2. md
3. sm
So the orderdetail table could have the following records (I’ve comma delimited the columns)
OrderId ItemId CustomerId Size
1,1,30,lr
1,1,30,md
1,1,30,sm
2,1,30,lr
2,1,30,md
3,1,30,lr
3,1,30,sm
4,1,30,lr
5,1,30,md
6,2,30,sm
7,3,30,md
8,3,30,lr
What I’d like is a really efficient query (there’s millions of records in the order details tables) that has the following output for a given customerId (30 in this case)
ItemId SizeLr SizeMd SizeSm
1 4 3 2
2 0 0 1
3 1 1 0
The query I’m using uses 3 group by queries (one each for “lr”, “md” and “sm”) and as a result it scans the table 3 times.
I’m looking for a solution that scans the table just onces. I think the solution is using the new Grouping Set feature in MSSQL 2008. But either ways, a solution using one scan if what I hope someone can help me with.
EDIT
The actual output needs to have other fields from the customer table and the order details table as well. These other fields are not dependent on the aggregates.
For example
ItemName ItemId SizeLr SizeMd SizeSm
A 1 4 3 2
B 2 0 0 1
C 3 1 1 0
Totals 5 4 4
It would nice if I could get the totals for each of the Size columns as well
How about this: