将SQL脚本更改为在一个字段上输出到自己的字段

时间:2013-08-05 09:34:35

标签: sql-server tsql

我有以下CTE和CTE查询def是我遇到问题的部分。我想做的是以某种方式输出CTE查询def结果以产生一个表,以便每个字段(例如'GreaterThan350')作为字段标题输出,并且计数显示为记录。 下面的脚本不是一成不变的(使用CTE的IE)我可以使用CTE的结果解决方案。

像这样:

enter image description here

而不是这样:

enter image description here

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

1 个答案:

答案 0 :(得分:1)

最简单的方法:

SELECT Sum(CASE WHEN NumberOfDaysSinceOrderDate < '40' THEN 1 ELSE 0 END) As LessThan40
     , Sum(CASE WHEN NumberOfDaysSinceOrderDate BETWEEN '40' AND '70' THEN 1 ELSE 0 END) As Between40AND70
     , etc...