1

询问:

SELECT          
         item_descr
        ,shop_id
        ,COUNT(item_descr) as times
from [Order] 
group  by item_descr , shop_id
order by shop_id , times desc

结果:

item_descr  shop_id    times
product A     shop1      5
product B     shop1      3
product A     shop2      6
product B     shop2      2

预期成绩:

item_descr   shop1   shop2 
product A     5        6
product B     3        2

如何更改查询以达到预期结果?

4

2 回答 2

0

在 SQL-Server 2005+ 中,您可以使用PIVOT。或者试试这个

SELECT          
         item_descr
        ,sum(case when shop_id='shop1' then times end) as shop1
        ,sum(case when shop_id='shop2' then times end) as shop2        
from [Order] 
group  by item_descr
order by item_descr
于 2013-05-30T12:18:16.510 回答
0

使用枢轴

Select item_descr, [shop1], [Shop2]
from 
(
  Select item_descr, shop_id, times
  from [Order]  
)p
pivot 
(
  sum(times)
  for shop_id in ([shop1], [Shop2])
)pvt;

SQL FIDDLE中的演示

于 2013-05-30T12:46:54.067 回答