How many stores are there?

来源: 2009-06-21 00:30:31 [旧帖] [给我悄悄话] 本文已被阅读:
Each store needs a column for total quantity on each item. If total number of stores varies every time you run the query, you need to write a stored procedure to determine the total number of stores first, and then use the dynamic SQL to create a temporary table has enough columns for each store.

If total number of stores is fixed, you can code the SQL as follows:

select item,
sum(case when store = 1 then qty else 0 end)'store1',
sum(case when store = 2 then qty else 0 end)'store2',
sum(case when store = 3 then qty else 0 end)'store3',
sum(case when store = 4 then qty else 0 end)'store4',
sum(qty)'total'
from tblname
group by item
order by item