SQL中Sum字段的计算

时间:2018-03-05 08:22:42

标签: mysql sql

我有一个查询,它按付款方式返回一个总和组

select
RTRIM(shopNo) as Shop_Number,
REPLACE(CONVERT(VARCHAR(10), DateTransaction, 103), '/', '') AS Todays_Date,
CodeModeDePaiement as Mode_Of_Payment,
SUM(convert(DOUBLE PRECISION,  Amount * 100 ) * 10) As Amount
from InvoiceSettlement
where  CodeModeDePaiement in 
(101,130,132,135,104,103,124,107,
136,117,131,410,106,122,109,102,105,112,133,999)
and   DateTransaction =  '2017/12/31' 
group by ShopNo,DateTransaction,CodeModeDePaiement

输出结果如下:

Shop_Number Todays_Date Mode_Of_Payment Amount
  2         31122017    102             18421610
  2         31122017    130             2332371390
  2         31122017    132             1082810
  2         31122017    106             66457640
  2         31122017    117             23925000
  2         31122017    133             5700000
  2         31122017    999             -490653940
  2         31122017    101             2404194870

我希望结果始终显示Mode_of_Payment(101 + 999)的总金额为101.我需要如下结果:

Shop_Number Todays_Date Mode_Of_Payment Amount
  2         31122017    102             18421610
  2         31122017    130             2332371390
  2         31122017    132             1082810
  2         31122017    106             66457640
  2         31122017    117             23925000
  2         31122017    133             5700000
  2         31122017    101             1913540930

1 个答案:

答案 0 :(得分:2)

使用CASE表达式将101和999映射到同一个东西:

SELECT
    RTRIM(shopNo) AS Shop_Number,
    REPLACE(CONVERT(VARCHAR(10), DateTransaction, 103), '/', '') AS Todays_Date,
    CASE WHEN CodeModeDePaiement IN (101, 999)
         THEN 101
         ELSE CodeModeDePaiement END as Mode_Of_Payment,
    SUM(CONVERT(DOUBLE PRECISION,  Amount * 100 ) * 10) AS Amount
FROM InvoiceSettlement
WHERE CodeModeDePaiement IN (101, 130, 132, 135, 104, 103, 124, 107, 136, 117,
    131, 410, 106, 122, 109, 102, 105, 112, 133, 999) AND
    DateTransaction = '2017/12/31' 
GROUP BY
    ShopNo,
    DateTransaction,
    CASE WHEN CodeModeDePaiement IN (101, 999)
         THEN 101
         ELSE CodeModeDePaiement END;