[英]T-SQL GROUP BY with Count () and Calculations Not grouping and Counting correctly
我編寫代碼的目的是為了對“ CurrentStatus”進行分組,將“ IN”和“ OUT”的記錄數除以“ currentstatus”,然后將“ OUT”記錄除以特定“ CurrentStatus”的記錄總數根據“ CurrentStatus”(IN + OUT)的總數記錄獲得“ CurrentStatus”中“ OUT”的百分比。下面是代碼片段。
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”總數(而不是CurrentStatus),“ OUT”是按通道的“ OUT”總數,“ TOTAL”是按“ CurrentStatus”。我希望代碼按CurrentStatus的“ IN”,“ OUT”和“ TOTAL”分組。有人可以幫忙嗎?
;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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.