得到了這個問題我想有人幫我解決。我認爲在程序代碼中解決問題會更容易,但我開始重新思考這個想法。在查詢中插入固定值
使用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
的SPRO c使用:
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.
@JohnSaunders,注意從SQL方面採取刺傷了嗎?謝謝! – Risho 2013-03-07 21:39:11