我编写代码的目的是在" CurrentStatus"进行分组,按照" currentstatus"计算记录数量。这是" IN'然后" OUT"然后划分" OUT"记录按特定" CurrentStatus"的记录总数。通过" CurrentStatus"的总数记录(IN + OUT)获得" OUT"的百分比在" CurrentStatus"。下面是代码片段。
SELECT DISTINCT
convert(date, Getdate(), 1) [Date],
channel,
CurrentStatus,
(select count(number) from dbo.vw_AP where channel = 'C' AND [In/Out of Tolerance] = 'in') [In],
(select count(number) from dbo.vw_AP where channel = 'C' AND [In/Out of Tolerance] = 'out') [Out],
count(number) [Total],
convert(Decimal(18,2), (1.0 * (select count(number) from dbo.vw_AgedPipeline where channel = 'C' AND [In/Out of Tolerance] = 'out') / count(number))) [OOTP]
FROM [dbo].[vw_AgedPipeline]
WHERE Channel = 'C'
GROUP BY CurrentStatus, channel
order by Channel, CurrentStatus

此代码带来的结果" IN"是" IN'的总数。通过Channel(而不是CurrentStatus)," OUT"是" OUT"的总数。通过频道和" TOTAL"是" CurrentStatus"的总数。我希望代码按照CurrentStatus进行分组,用于" IN"," OUT"和" TOTAL"。有人可以帮忙吗?
答案 0 :(得分:0)
;WITH CTE AS
(SELECT
convert(date, Getdate(), 1) [Date]
,v.channel
,v.CurrentStatus
,count(CASE WHEN A.[In/Out of Tolerance] = 'in' THEN 1 ELSE NULL END) [In]
,count(CASE WHEN A.[In/Out of Tolerance] = 'out' THEN 1 ELSE NULL END) [Out]
,count(v.number) [Total]
FROM [dbo].[vw_AgedPipeline] V
INNER JOIN dbo.vw_AP A ON v.Channel = A.Channel
WHERE V.Channel = 'C'
GROUP BY v.channel,v.CurrentStatus
order by v.channel,v.CurrentStatus
)
SELECT [Date]
,channel
,CurrentStatus
,[In]
,[Out]
,[Total]
,convert(Decimal(18,2), (1.0 * [Out]) / ([Total] * 1.0)) [OOTP]
FROM CTE