SQL sum列取决于其他列的值

时间:2014-11-02 06:48:06

标签: sql-server lookup

我有一张包含字段的表格:

Doc_No , Doc_Type , Item_No , Added_Qty ,Deducted_Qty 

我需要一个基于

返回结果集的查询
  • if Doc_Type= "2" then select sum(Added_Qty) AS SUM_Added_Qty
  • if Doc_Type= "7" then select sum(Deducted_Qty) AS SUM_Deducted_Qty

并显示SUM_Added_Qty - SUM_Deducted_Qty AS Stock

结果必须在同一行

--------------------------------------------------------
| Item_No  |  SUM_Added_Qty |  SUM_Deducted_Qty | Stock|
--------------------------------------------------------

感谢您的帮助!

(系统是Sql server)

1 个答案:

答案 0 :(得分:0)

SELECT Item_No,
        SUM(CASE WHEN Doc_Type = '2' THEN Added_Qty ELSE 0 END) SUM_Added_Qty,
        SUM(CASE WHEN Doc_Type = '7' THEN Deducted_Qty ELSE 0 END) SUM_Deducted_Qty,
        SUM(CASE WHEN Doc_Type = '2' THEN Added_Qty
                 WHEN Doc_Type = '7' THEN -Deducted_Qty
                 ELSE 0 END) Stock
FROM YourTable
GROUP BY Item_No