我在mySQL中有一个表,其中包含以下列:
CUSTOMER_CODE | TRANS_TYPE | TRANS_VALUE
TRANS_TYPE可以是“DRINV”(销售)或“DRCDT”(信用卡)。
我想获得每位客户的总销售额,所以到目前为止我的查询是:
SELECT CUSTOMER_CODE, SUM(TRANS_VALUE) as SALES FROM DR_TRANS GROUP BY CUSTOMER_CODE
问题在于这是销售和信用额的总和,而不是给予销售额减去信用额。我希望结果是
SUM(TRANS_VALUE) where TRANS_TYPE = "DRINV" - SUM(TRANS_VALUE) where TRANS_TYPE = "DRCDT".
是否可以在SQL查询中执行此操作?
答案 0 :(得分:6)
select customer_code,
sum(case
when trans_type = 'DRINV' then
trans_value
else
-trans_value
end) as net_sales
from dr_trans
group by customer_code
答案 1 :(得分:1)
是的,有可能。使用CASE子句:
SELECT CUSTOMER_CODE,
SUM(CASE WHEN TRANS_TYPE = 'DRINV' THEN TRANS_VALUE ELSE (- TRANS_VALUE) END ) as SALES
FROM DR_TRANS GROUP BY CUSTOMER_CODE