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
答案 0 :(得分: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];