SQL中Sum字段的计算

问题描述 投票:1回答:1

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

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
mysql sql
1个回答
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;     
© www.soinside.com 2019 - 2024. All rights reserved.