SQL Server数据透视挑战

时间:2014-12-22 13:32:41

标签: sql sql-server select pivot unpivot

有两个给定的列 - 前缀和日期时间,例如

PREFIX | DATETIME

ABC    | 2010-01-28 07:11:31.000

DEF    | 2010-02-15 07:11:31.000

DEF    | 2010-01-25 07:11:31.000

我想按年/月和前缀透视数据。 结果应如下所示:

YEAR   | MONTH | ABC | DEF |

2010   | Jan   |  1  |  1  |

2010   | Feb   |  0  |  1  |

换句话说,计算具有相同前缀的对象具有相同的句点(年/月)。

我试过这段代码,但它没有用,我不知道问题出在哪里。

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

select @cols = STUFF((SELECT ',' + QUOTENAME(O.OU01) 
                from Test.dbo.Organisation as O
                group by O.OU01
                order by O.OU01
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

set @query = 'SELECT [Year], [month], ' + @cols + ' 
        from 
        (
           SELECT Year(A.Stand) Year,
             Datename(month, A.Stand) [month],
             O.OU01
           FROM Test.dbo.Assets as A
           join Test.dbo.Organisation as O on A.Key = O.Key
        ) x
        pivot 
       (
            Count([O.OU01])
            for O.OU01 in (' + @cols + ')
        ) p '

execute(@query)

2 个答案:

答案 0 :(得分:2)

使用Conditional Aggregate

SELECT Year([DATETIME]) [Year],
       Datename(month, [DATETIME]) [month],
       Count(CASE WHEN PREFIX = 'ABC' THEN 1 END) ABC,
       Count(CASE WHEN PREFIX = 'DEF' THEN 1 END) DEF
FROM   Tablename
GROUP  BY Year([DATETIME]),
          Datename(month, [DATETIME]) 

或使用Pivot

SELECT *
FROM   (SELECT Year([DATETIME])            [Year],
               Datename(month, [DATETIME]) [month],
               PREFIX,
               [DATETIME]
        FROM   tablename) a
       PIVOT (Count([DATETIME])
             FOR PREFIX IN ([ABC],
                            [DEF])) AS P 

SQLFIDDLE DEMO

动态版本:

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

select @cols = STUFF((SELECT ',' + QUOTENAME(PREFIX) 
                    from es
                    group by PREFIX
                    order by PREFIX
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT [Year], [month], ' + @cols + ' 
            from 
            (
               SELECT Year(DATETIMEs)            Year,
                 Datename(month, DATETIMEs) [month],
                 PREFIX
               FROM es
            ) x
            pivot 
            (
                Count([PREFIX])
                for PREFIX in (' + @cols + ')
            ) p '

execute(@query)

Demo

答案 1 :(得分:1)

使用SQL Server的 PIVOT TABLE

试试这个:

SELECT Year, MonthName, [ABC], [DEF]
FROM (SELECT YEAR(A.DATETIME) AS Year, DATENAME(A.DATETIME,Getdate()) AS MonthName, 
             A.PREFIX  AS Header, A.DATETIME DATA 
        FROM tableA A
     ) AS A 
PIVOT(COUNT(DATA) FOR Header IN ([ABC], [DEF])) AS P