SQL - sum of some rows, minus sum of other rows

前端 未结 2 557
我寻月下人不归
我寻月下人不归 2021-01-23 11:53

I have a table in mySQL with the following columns:

CUSTOMER_CODE | TRANS_TYPE | TRANS_VALUE

TRANS_TYPE could be either \"DRINV\" (a sale) or \

相关标签:
2条回答
  • 2021-01-23 12:16
    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
    
    0 讨论(0)
  • Yes, it is possible. Use CASE caluse:

    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
    
    0 讨论(0)
提交回复
热议问题