2014-11-02 48 views
0

我有很大的表151列 - 每列表示一个商店(150商店* 1列)加上一个日期列。Sql查询从列转换为行

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., 
+0

检查的[逆透视与列名]我的回答 – 2014-11-02 09:45:32

+0

可能重复(http://stackoverflow.com/questions/19055902/unpivot-with-column-name) – 2014-11-02 10:05:35

回答

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 
+0

优秀Ganesh先生。我刚刚注册并从未期待如此快速的回应。 – 2014-11-02 14:14:19

+0

@MohanYGK欢迎您如果您认为这有帮助,请将其标记为答案 – 2014-11-02 14:15:45

+0

我们正在为包括生产,库存,零售管理,工资,财务等在内的150个零售店实施AX 2012,我正在寻找我的IT经理职位公司。我不知道你的背景和兴趣,但如果你有兴趣,请告诉我。 – 2014-11-02 14:16:09