如何使用mySQL对表中的数字求和

时间:2018-03-06 19:00:26

标签: mysql

我正在使用phpMyAdmin,我有两个表:

___ SalesTaxes

|--------|----------|------------|
| STX_Id | STX_Name | STX_Amount |
|--------|----------|------------|
|      1 |    Tax 1 |       5.00 |
|      2 |    Tax 2 |      13.50 |
|--------|----------|------------|

___ BillableDatas

|--------|---------------|------------|------------|----------|---------------------|
| BIL_Id | BIL_BookingId | BIL_Date   | BIL_Status | BIL_Rate | BIL_ApplicableTaxes |
|--------|---------------|------------|------------|----------|---------------------|
|      1 |             2 | 2018-03-06 | notcharged |   100.00 |                   1 |
|      2 |             2 | 2018-03-07 | notcharged |   105.00 |                 1,2 |
|--------|---------------|------------|------------|----------|---------------------|

我希望每天列出___BillableDatas中的可结算内容列表,具体取决于事物的状态(收费与未收费)。

这样的事情:

|------------|-----------------|--------------------|------------------|--------------------|
|    Date    | BIL_Sum_Charged | BIL_Sum_Notcharged | Taxes_ForCharged | TaxesForNotCharged |
|------------|-----------------|--------------------|------------------|--------------------|
| 2018-03-06 |            0.00 |             100.00 |             0.00 |               5.00 |
| 2018-03-07 |            0.00 |             105.00 |             0.00 |              19.42 |
|------------|-----------------|--------------------|------------------|--------------------|

请注意,以下查询返回上一个表(仅前3列):

SELECT BIL_Date, 
ifnull(sum(case when BIL_Status = "charged" then BIL_Rate else 0 end), 0) 
as BIL_Sum_Charged, 
ifnull(sum(case when BIL_Status = "notcharged" then BIL_Rate else 0 end), 0) 
as BIL_Sum_Notcharged 
FROM ___BillableDatas 
WHERE BIL_HotelId='cus_CNHLMiMOzP5cuM' 
AND BIL_BookingId='2' 
GROUP BY BIL_Date 
ORDER BY BIL_Date 
ASC

如何生成其他两列?

请参阅SQL小提琴: http://sqlfiddle.com/#!9/e1208e/2

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

您可以使用FIND_IN_SET加入Tax和Billable表,然后汇总税额:

SELECT b.BIL_Date, 
ifnull(sum(case when b.BIL_Status = "charged" then b.BIL_Rate else 0 end), 0) 
as BIL_Sum_Charged, 
ifnull(sum(case when b.BIL_Status = "notcharged" then b.BIL_Rate else 0 end), 0) 
as BIL_Sum_Notcharged,
ifnull(sum(case when b.BIL_status = "charged" then s.STX_Amount else 0 end), 0) 
as STX_TAX_Charged,
ifnull(sum(case when b.BIL_status = "notcharged" then s.STX_Amount else 0 end), 0) 
as STX_TAX_NotCharged
FROM ___BillableDatas b
INNER JOIN ___SalesTaxes s
ON FIND_IN_SET(s.STX_id, b.BIL_ApplicableTaxes) > 0
WHERE b.BIL_HotelId='cus_CNHLMiMOzP5cuM' 
AND b.BIL_BookingId='2' 
GROUP BY b.BIL_Date 
ORDER BY b.BIL_Date 
ASC