以下SQL输出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)
答案 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);