Sql Query从列转换为行

时间:2014-11-02 09:12:23

标签: sql-server

我有非常大的表151列 - 每列代表一个商店(150个商店* 1列)加上一个日期列。

Date         Store001       Store002      Store003      Store004 ................... Store150
---------------------------------------------------------------------------------------------------    
01/01/14     12560          8546           7468          10154                        16845

31/10/14     13978          7584           8456          13458                        25458

我需要的结果如下:

Date         Store#        Amount
-----------------------------------
01/01/14     Store001      12560
01/01/14     Store002      8546
01/01/14     Store003      7468
01/01/14     Store004      10154
etc.,

1 个答案:

答案 0 :(得分:0)

Create table yourtable([Date]  date,Store001 int ,Store002 int)
insert into yourtable ([Date],Store001,Store002)
values
(GETDATE(),1243,546),
(GETDATE(),4545,798),
(GETDATE(),5687,456),
(GETDATE(),0756,685)

简单查询

   ;WITH CTE
AS
  (
  SELECT * FROM (
  SELECT [Date],Store001,Store002 FROM yourtable) T
  UNPIVOT ( Value FOR N IN (Store001,Store002))P
  )
 SELECT [Date],N as Store#,SUM(Value) as Amount
 FROM CTE
 GROUP BY [Date],N

动态SQL

declare @cols nvarchar(max) 
select @cols = coalesce(@cols+N',', N'') + quotename(c.name) from syscolumns c
inner join sysobjects o on c.id = o.id and o.xtype = 'u'
where o.name = 'yourtable' and c.name not in ('Date') order by c.colid
select @cols
declare @query nvarchar(max) 

select @query = N'
 ;WITH CTE
AS
  (
  SELECT * FROM (
  SELECT [Date], ' + @cols + '
FROM yourtable) T
  UNPIVOT ( Value FOR N IN (' + @cols + '))P
  )
 SELECT [Date],N as Store#,SUM(Value) as Amount
 FROM CTE
 GROUP BY [Date],N
'
print @query 
exec sp_executesql @query 

<强>输出

Date         Store#     Amount
2014-11-02  Store001    12231
2014-11-02  Store002    2485