2017-09-25 228 views
0

我需要[Contribution]的查詢。我用這個查詢:SQL Server中的多個聚合函數

with ttt as  
( 
select 
(DYG.U_StyleId)[DYG Style]  
,Max(O1.CardCode) [Party Group Code], 
MAX(O1.CardName) [Party Group Name]  
,MAX(OR1.DocDate) [Date]  
,sum(CONVERT(NUMERIC(15,2),(RDR1.PriceBefDi*RDR1.Quantity))) [JobAmount]  
,CONVERT(NUMERIC(15,2),SUM(RDR1.Quantity)) [Mtr]  
,CONVERT(NUMERIC(15,2),SUM(RDR1.U_Pcs))[Pcs]  
,(select sum(RDR1.PriceBefDi*RDR1.Quantity) from RDR1) tqty  

from 
ORDR OR1  
left join RDR1 on RDR1.DocEntry = OR1.DocEntry  
left join OITM on RDR1.ItemCode = oitm.ItemCode  
LEFT JOIN OCRD ON OCRD.CardCode = OR1.CardCode  
LEFT JOIN OCRG ON OCRG.GroupCode = OCRD.GroupCode  
LEFT JOIN OCRD O1 ON O1.U_BCode = OCRD.U_GrpCod 
LEFT JOIN 
(SELECT U_StyleId FROM RDR1 WHERE U_StyleId in 
('BLOOM','BLOOMING','DYD','DYD-R','DYED','Ex.CLR.','RAINBOW')) 
DYG ON DYG.U_StyleId = RDR1.U_StyleId  
    group by 
     DYG.U_StyleId  
        ) 
    select 
    Style, [Party Group Code], 
    [Party Group Name], JobAmount, 
    (sum(JobAmount)/tqty * 100) [Contribution], 
    [Date], [Pcs] 
from 
    ttt 
    group by 
     Style 

我需要最後jobamount的總和除以上面的tqty。 但它顯示此錯誤。

'列'ttt.Party組代碼'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。'

請用我的查詢來獲得合適的[貢獻]金額。

回答

1

試試這個:

select Style,[Party Group Code],[Party Group Name],JobAmount,[Date],[Pcs], 
     100.0 * (sum(JobAmount) OVER (PARTITION BY Style))/tqty [Contribution] 
    from ttt; 
+0

請檢查我的版本有問題 – Bha15