遇到这个问题,想找人帮我解决。我认为在程序代码中解决问题会更容易,但我开始重新考虑这个想法。
PIVOT
使用从语句中提取数据的 SQL 查询,SELECT
其中一个字段[Cat_Entries]
是用作单元格标签的硬编码值。Cat_Entries 的值是使用COUNT(EventGUID)
和/或CAST(SUM(Duration) AS varchar(10)) AS TotalRepairTime
在相同句子中计算的。
从SELECT
下面的语句中,您可以看到使用UNION
三个查询中的一个来生成输出。但是,如果“子查询”作为计算结果没有返回值。然而,要求是 [Cat_Entries]
无论值如何都显示标签。
以下是数据现在的样子:
Cat Cat Entries 6/1/2012 7/1/2012 8/1/2012 9/1/2012
------ -------------------- -------- -------- -------- --------
00000A Critical Down Time 1
00000A Critical Outage 1
00000A Total Repair Time 65
00000B Critical Down Time 6
00000B Total Repair Time 90
00000C Critical Down Time 1 5
00000C Critical Outage 1 5
00000C Total Repair Time 30 240
00000D Critical Down Time 2
00000E Critical Down Time 1
00000G Critical Down Time 1
00000M Critical Down Time 1 3
00000M Critical Outage 1 3
00000M Total Repair Time 60 180
...这就是所需输出的样子(** 表示插入的空行):
Cat Cat Entrie s 6/1/2012 7/1/2012 8/1/2012 9/1/2012
------ -------------------- -------- -------- -------- --------
00000A Critical Down Time 1
00000A Critical Outage 1
00000A Total Repair Time 65
00000B Critical Down Time 6
** 00000B Critical Outage
00000B Total Repair Time 90
00000C Critical Down Time 1 5
00000C Critical Outage 1 5
00000C Total Repair Time 30 240
00000D Critical Down Time 2
** 00000D Critical Outage
** 00000D Total Repair Time
这是存储过程PIVOT
:
SELECT @cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT '],[' + cast([Year] as varchar(4))
FROM vCatCountByMonthYear where SiteGUID = @SiteGuid
and [Year] BETWEEN @StartDate AND @StopDate ORDER BY '],[' + cast([Year] as varchar(4))
FOR XML PATH('') ), 1, 2, '') + ']'
SET @query = N'SELECT Cat,[Cat_Entries], ' + @cols +' FROM (SELECT Cat,[Year],
[Cat_Entries],Value,OrderBy FROM vCatCountByMonthYear
where SiteGUID = ' + CHAR(39) + CONVERT(nvarchar(36), @SiteGuid) + CHAR(39) + ' and
[Year] BETWEEN ' + CHAR(39) + @StartDate + CHAR(39) + ' AND ' + CHAR(39) +
@StopDate + CHAR(39) + ' ) p PIVOT ( Sum ([Value] ) FOR [Year] IN ( '+ @cols +' ) )
AS pvt ORDER BY Cat,OrderBy'
execute(@query)
...这是VIEW
存储过程使用的:
SELECT SiteGUID, Cat_Entries, EntriesCount AS Value,
CONVERT(date, CAST(Month AS varchar(2)) + '-1-' + CAST(Year AS varchar(4))) AS MonthYear,
Month, Year, OrderBy, Cat, EventId
FROM (SELECT SiteGUID, 'Critical Down Time' AS Cat_Entries, COUNT(EventGUID) AS EntriesCount,
Month, Year, 1 AS OrderBy, Cat, EventId
FROM dbo.vCatCountTotalEntries
GROUP BY SiteGUID, Month, Year, Cat, EventId
UNION
SELECT SiteGUID, 'Critical Outage' AS Cat_Entries, COUNT(EventGUID) AS EntriesCount,
Month, Year, 2 AS OrderBy, Cat, EventId
FROM dbo.vCatCountEqpEntries
GROUP BY SiteGUID, Cat, Month, Year, Cat, EventId
UNION
SELECT SiteGUID, 'Total Repair Time' AS Cat_Entries,
CAST(SUM(Duration) AS varchar(10)) AS TotalRepairTime, Month, Year, 3 AS OrderBy,
Cat, EventId
FROM dbo.vCatCountOnEqpRprTm
GROUP BY SiteGUID, Cat, Month, Year, Cat, EventId) AS W
一如既往,我感谢您的时间和努力!R。