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

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

我正在使用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

非常感谢你的帮助。

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