透视查询 - SQL Server 2005

时间:2012-11-26 11:28:54

标签: sql sql-server sql-server-2005 pivot

我在SQL Server 2005中有以下查询,它获取下面提到的结果。

select Distinct(date),id,
           sum(convert(float,Gross)),
           count(*) as no from Daily
    group by date,id 
    order by date desc

Date                     id          Gross          Count
2012-11-25 00:00:00.000  Client id1  1232.6140752   12
2012-11-25 00:00:00.000  Client id2  1183.75621528  88
2012-11-26 00:00:00.000  Client id3  4561.459086    67
2012-11-26 00:00:00.000  Client id4  6781.15660608  440

现在我如何以下列格式获得结果。这看起来像一个数据透视查询请求帮助

id           Date1  Date2  Date3  Date4  Date5 Date6 Date7
Client id1   Gross       
Client id2   Gross
Client id3   Gross

2 个答案:

答案 0 :(得分:2)

有两种方法可以PIVOT,可以是硬编码所有日期值的静态版本,也可以是在运行时生成日期列表的动态版本。

静态版本:

如果您的日期数量有限,则您的查询将与此类似。

select id, [yourDate1], [yourDate2], [yourDate3]
from
(
  select date, id, cast(gross as float) as gross
  from Daily
) src
pivot
(
  sum(gross)
  for date in ([yourDate1], [yourDate2], [yourDate3])
) piv;

请参阅SQL Fiddle with Demo

动态版本:

此版本生成动态SQL以在运行时获取日期列表。您的代码与此类似:

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

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

set @query = 'SELECT id, ' + @cols + ' from 
             (
               select date, id, cast(gross as float) as gross
               from Daily
            ) src
            pivot 
            (
                sum(gross)
                for date in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

WITH a AS
(
    SELECT [Id], [Gross]
    , [DateRank] = DENSE_RANK() OVER (ORDER BY [Date])
    FROM [Daily]
)
SELECT *
FROM a PIVOT
(
    SUM([Gross])
    FOR [DateRank] IN ([1], [2], [3], [4], [5], [6], [7])
) b