2015-04-06 70 views
0

我編寫了代碼,目的是在「CurrentStatus」中進行分組,計算「currentstatus」記錄數爲「IN」和「OUT」 「,然後用」CurrentStatus「的總數記錄(IN + OUT)將」OUT「記錄除以特定」CurrentStatus「的記錄總數,以獲得」CurrentStatus「中的」OUT「的百分比。是代碼片段。帶有Count()和計算的T-SQL GROUP BY沒有正確分組和計數

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」的總數。我希望代碼按「IN」,「OUT」和「TOTAL」按CurrentStatus進行分組。誰能幫忙?

+0

哪個DBMS? sqlserver <> mysql –

回答

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