2017-01-13 52 views
0
SELECT I.[Order Number], SUM(CAST([Ext Price] AS FLOAT)) AS Rev 
     FROM stg.Invoices I 
     where i.[order number] = '64100097' 
     GROUP BY I.[Order Number] 

每一行的百分比給我:發現的總

Order Number Rev 
64100097 124079.33 

當我嘗試使用,讓每線收入的%:

SELECT StgID, 
CAST((CAST([Ext Price] AS FLOAT))/(NULLIF(Rev,0)) AS FLOAT) 
FROM stg.Invoices I 
JOIN (
     SELECT I.[Order Number], 
     SUM(CAST([Ext Price] AS FLOAT)) AS Rev 
     FROM stg.Invoices I 
     where i.[order number] = '64100097' 
     GROUP BY I.[Order Number] 
) as TotRev on I.[Order Number] = TotRev.[Order Number] 

我得到這個:

StgID RevPct 
7006418 0.202934687026437 
7006427 0.000460995397057673 
7006417 0.0274442971282969 
7006426 0.000415379418957211 
7006422 0.0312703171430729 
7006425 0.000609287622684616 
7006424 0.0161187201768417 
7006420 0.197365669205338 
7006419 0.226870986489047 
7006428 0.000134752500678397 
7006421 0.10299056256993 
7006423 0.193384345321658 

其中總計高達:.08333333333

這不應該加1嗎?

我不明白爲什麼我不能讓每一行的總和達到100%。

這裏是證明所有的人都應該加起來總:

select stgid, [ext price] 
from stg.Invoices 
where [order number] = '64100097' 


stgid ext price 
7006420 24489 
7006418 25180 
7006427 57.2 
7006417 3405.27 
7006426 51.54 
7006421 12779 
7006423 23995 
7006422 3880 
7006425 75.6 
7006424 2000 
7006419 28150 
7006428 16.72 
+1

不要重複使用表的別名。這太混亂了。 – jarlh

+1

你的號碼加起來超過0.083。第一個是0.20。 –

回答

1

使用窗口功能:

SELECT I.[Order Number], SUM(CAST([Ext Price] AS FLOAT)) AS Rev , 
     SUM(CAST([Ext Price] AS FLOAT))/NULLIF(SUM(SUM(CAST([Ext Price] AS FLOAT))) OVER(), 0) as p_rev 
FROM stg.Invoices I 
WHERE i.[order number] = '64100097' 
GROUP BY I.[Order Number]; 
相關問題