2017-05-18 52 views
1

SQL Server專家的問題。在下面的查詢中,我希望有一個額外的列,它也是SUM數量,但是基於不同的需求類型。我嘗試了一些想法 - CASE並在選擇列表中添加子查詢,但都返回了太多結果。我希望看到的是MATERIAL,MATERIAL_DESCRIPTION,SIZE_LITERAL,當需求類型='PB'時的數量總和,當需求類型='01'時的數量總和不確定如何在兩個不同的條件下兩次添加數量。在此先感謝同一列在查詢中多次出現

SELECT MATERIAL, 
     MATERIAL_DESCRIPTION, 
     SIZE_LITERAL, 
     SUM(QUANTITY) AS 'SUM_FCST' 

FROM VW_MRP_ALLOCATION 

WHERE REQUIREMENT_CATEGORY = 'A60381002' 

AND MATERIAL_AVAILABILITY_DATE >= GETDATE() 

AND REQUIREMENT_TYPE ='PB' 


GROUP BY MATERIAL, 
     MATERIAL_DESCRIPTION, 
     SIZE_LITERAL 

ORDER BY MATERIAL, 
     SIZE_LITERAL 
+1

條件的總和。其中兩個......並刪除從第 – xQbert

回答

6

你會使用一個CASE表達SUM()內。這是有條件的聚集:

SELECT MATERIAL, 
     MATERIAL_DESCRIPTION, 
     SIZE_LITERAL, 
     SUM(case when REQUIREMENT_TYPE ='PB' then QUANTITY else 0 end) AS 'SUM_FCST_PB', 
     SUM(case when REQUIREMENT_TYPE ='01' then QUANTITY else 0 end) AS 'SUM_FCST_01'  
FROM VW_MRP_ALLOCATION 
WHERE REQUIREMENT_CATEGORY = 'A60381002' 
    AND MATERIAL_AVAILABILITY_DATE >= GETDATE() 
GROUP BY MATERIAL, 
     MATERIAL_DESCRIPTION, 
     SIZE_LITERAL 
ORDER BY MATERIAL, 
     SIZE_LITERAL 
+2

哪裏刪除條款的限制! – xQbert

+0

輝煌 - 並且謝謝 - 問題 - 如果您沒有ELSE 0 END - 而只是結束,它會繼續工作嗎?如果不是爲什麼不呢?我感謝 – user3496218

+0

@ user3496218的幫助區別在於'else 0'會在沒有匹配的行中插入一個零值,否則它就會爲空。這取決於你想如何出現 - [這裏是一個演示](http://data.stackexchange.com/stackoverflow/query/673031)。 – ollie

1

您可以使用內部和情況如下:使用case語句

SELECT MATERIAL, 
     MATERIAL_DESCRIPTION, 
     SIZE_LITERAL, 
     SUM(CASE WHEN [Requirement_Type] = 'PB' then QUANTITY else 0 end) AS 'SUM_FCST' 

FROM VW_MRP_ALLOCATION 

WHERE REQUIREMENT_CATEGORY = 'A60381002' 

AND MATERIAL_AVAILABILITY_DATE >= GETDATE() 

AND REQUIREMENT_TYPE ='PB' 


GROUP BY MATERIAL, 
     MATERIAL_DESCRIPTION, 
     SIZE_LITERAL 

ORDER BY MATERIAL, 
     SIZE_LITERAL 
相關問題