按列

时间:2015-05-27 15:41:37

标签: sql sql-server pivot

以下SQL输出3列:

  1. 日期(第1栏)YYYY-DD
  2. MeterReadTypeDescription
  3. 日期重复,因为可以有一个或多个MeterReadTypeDescription

    我想要的是能够转动,以便数据具有每个MeterReadTypeDescription的动态列标题,并且低于总数。这意味着第一列中的日期将是唯一的

    如何基于MeterReadTypeDescription转移此SQL?

    SELECT 
      convert(char(7), MeterReadDate, 121),
      MeterReadTypes.MeterReadTypeDescription, 
      count(*) as total    
    FROM 
      [PremiseMeterReadProviders],
      MeterReadTypes    
    WHERE 
      [PremiseMeterReadProviders].MeterReadTypeId = MeterReadTypes.MeterReadTypeId 
      and (MeterReadDate > dateadd(m,-12,getdate()))
    GROUP BY
      convert(char(7), MeterReadDate, 121),
      MeterReadTypes.MeterReadTypeDescription
    ORDER BY 
      convert(char(7), MeterReadDate, 121)
    

1 个答案:

答案 0 :(得分:2)

让它工作(感谢igloo链接)...

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

SELECT @cols = STUFF((SELECT distinct 
                        ',' +
                        QUOTENAME(MeterReadType)
                 FROM MeterReadView with (nolock)
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');

SET @query = ' SELECT MeterReadMonth as Month,  ' + @cols + ' 

FROM 
(
   SELECT MeterReadType, MeterReadMonth,isnull(total,0) as total
   FROM [MeterReadView] with (nolock)
) t
PIVOT
( 
  sum(total)
  FOR MeterReadType IN (' + @cols + ' )
) 
p ' ;

Execute(@query);