SQL Server专家的问题。在下面的查询中,我希望有一个额外的列,它也是SUMs Quantity,但是基于不同的Requirement Type。我尝试了一些想法 - CASE并在选择列表中添加子查询但所有返回的结果都太多了。我希望看到的是MATERIAL,MATERIAL_DESCRIPTION,SIZE_LITERAL,QUANTTITY,当需要类型='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
答案 0 :(得分: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
答案 1 :(得分:1)
您可以在总和中使用案例如下:
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