我有以下 CTE,CTE 查询 def 是我遇到问题的部分。我想做的是以某种方式输出 CTE 查询定义结果以生成一个表,以便每个字段(例如“GreaterThan350”)作为字段标题输出,并且计数显示为记录。下面的脚本不是一成不变的(使用 CTE 的 IE)我对与 CTE 的结果一起工作的解决方案持开放态度。
像这样:
而不是这样:
WITH AgedCircGrouped_CTE(PWNum, NumberOfDaysSinceOrderDate, OrderDate, CurrentStage, CircuitID) AS
(
SELECT
cir.[PW Number] AS PWNum
--Get the correct number of working dayts since the order date by using the fn_WorkDays function
,CONVERT(VARCHAR(10),SharedInfo.dbo.fn_WorkDays(cir.[Install Date], GETDATE()),103) AS NumberOfDaysSinceOrderDate
,CONVERT(VARCHAR(10), ISNULL(cir.[Install Date],'01/01/1900'),103) AS OrderDate--Get the order dates
,ISNULL(cirRep.CurrentStage, 'Not Set') AS CurrentStage
,cir.[ID] as CircuitID
FROM Quotebase.dbo.Circuits cir
LEFT JOIN Quotebase.dbo.CircuitReports cirRep ON Cir.[PW Number] = CirRep.PWNumber
WHERE Cir.Status='New Circuit Order'
--ORDER BY Cir.[PW Number]
)
SELECT
COUNT ([NumberOfDaysSinceOrderDate] ) AS GreaterThan350
FROM [AgedCircGrouped_CTE]
WHERE [NumberOfDaysSinceOrderDate] > '350'
UNION ALL
SELECT
COUNT ([NumberOfDaysSinceOrderDate] ) AS Between250AND350
FROM [AgedCircGrouped_CTE]
WHERE [NumberOfDaysSinceOrderDate] BETWEEN '250' and '350'
UNION ALL
SELECT
COUNT ([NumberOfDaysSinceOrderDate] ) AS Between180AND250
FROM [AgedCircGrouped_CTE]
WHERE [NumberOfDaysSinceOrderDate] BETWEEN '180' and '250'
UNION ALL
SELECT
COUNT ([NumberOfDaysSinceOrderDate] ) AS Between120AND180
FROM [AgedCircGrouped_CTE]
WHERE [NumberOfDaysSinceOrderDate] BETWEEN '120' and '180'
UNION ALL
SELECT
COUNT ([NumberOfDaysSinceOrderDate] ) AS Between70AND120
FROM [AgedCircGrouped_CTE]
WHERE [NumberOfDaysSinceOrderDate] BETWEEN '70' and '120'
UNION ALL
SELECT
COUNT ([NumberOfDaysSinceOrderDate] ) AS Between40AND70
FROM [AgedCircGrouped_CTE]
WHERE [NumberOfDaysSinceOrderDate] BETWEEN '40' and '70'
UNION ALL
SELECT
COUNT ([NumberOfDaysSinceOrderDate] ) AS LessThan40
FROM [AgedCircGrouped_CTE]
WHERE [NumberOfDaysSinceOrderDate] < '40'
GO