0

我的输入是:

date      Costed   Celldata
8-Apr-13    1       15
15-Apr-13   1       24
22-Apr-13   1       36  

我需要输出为:

date       8-Apr-13  15-Apr-13 22-Apr-13
Costed        1         1          1         
Celldata     15         24         36        

我申请的查询是:

CREATE TABLE testing1(Spot_dt date, Costed INT, celldata INT)

INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-08',1,15);
INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-15',1,24);
INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-22',1,36);


DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Spot_dt) 
                    from testing1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT Costed,' + @cols + ' 
             from 
             (
                select Spot_dt, Costed, CellData
                from testing1
            ) x
            pivot 
            (
                min(CellData)
                for Spot_dt in (' + @cols + ')
            ) p '

execute(@query)

我收到的输出是:

8-Apr-13    15-Apr-13   22-Apr-13   
1           1           1           
15          24          36          

所以基本上我需要一个额外的列,在其中我可以将列标题作为行值。

4

1 回答 1

0

以下应该有效:

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Spot_dt) 
                    from testing1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT valtype dates, ' + @cols + ' 
              from (select Spot_dt, Costed, CellData from testing1) as x
              unpivot (vals for valtype in (Costed, celldata)) as u
              pivot (min(vals) for spot_dt in (' + @cols + ')) as p'

execute(@query)

(在围绕日期旋转数据之前,您需要取消旋转单独的列,以便初始数据集中的每一列在每个日期都有自己的行。)

SQLFiddle在这里

于 2013-04-25T08:24:42.823 回答