SQL数据透视表列和行

时间:2013-05-30 12:06:14

标签: sql sql-server-2008-r2 pivot

查询:

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

使用PIVOT

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

中的演示