我在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查询中执行此操作?
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