我有以下表结构:
表___BillableDatas
:
|--------|---------------|------------|----------|--------------|------------|
| BIL_Id | BIL_BookingId | BIL_Date | BIL_Rate | BIL_Quantity | BIL_Status |
|--------|---------------|------------|----------|--------------|------------|
| 1 | 21 | 2017-12-23 | 10.00 | 2 | charged |
| 2 | 21 | 2017-12-23 | 105.00 | 1 | charged |
| 3 | 21 | 2017-12-24 | 105.00 | 1 | charged |
| 4 | 21 | 2017-12-25 | 105.00 | 1 | notcharged |
| 5 | 21 | 2017-12-26 | 105.00 | 1 | notcharged |
| 6 | 21 | 2017-12-26 | 30.00 | 2 | charged |
|--------|---------------|------------|----------|--------------|------------|
我希望array
显示每天的项目总数,具体取决于状态charged
和notcharged
。
所需的输出应如下:
Array
(
[2017-12-23] => Array
(
[charged] => 125.00
[notcharged] => 0.00
)
[2017-12-24] => Array
(
[charged] => 105.00
[notcharged] => 0.00
)
[2017-12-25] => Array
(
[charged] => 0.00
[notcharged] => 105.00
)
[2017-12-26] => Array
(
[charged] => 30.00
[notcharged] => 105.00
)
)
我试过的查询:
select a.BIL_BookingId,a.BIL_Date,a.BIL_Rate*a.BIL_Quantity as total, a. BIL_Status
from ___BillableDatas as a
答案 0 :(得分:0)
有条件地总结,检查分组:
select a.BIL_BookingId
,a.BIL_Date
,CASE WHEN BIL_Status = 'charged' THEN a.BIL_Rate*a.BIL_Quantity ELSE 0 END as charged
,CASE WHEN BIL_Status = 'notcharged' THEN a.BIL_Rate*a.BIL_Quantity ELSE 0 END as notcharged
from ___BillableDatas as a
group by a.BIL_BookingId, a.BIL_Date
答案 1 :(得分:0)
你应该使用sum和group by(如果null,则为null时为0)
select BIL_Date,
ifnull(sum(case when BIL_Status ='charged' then BIL_Rate else 0 end), 0) as charged,
ifnull(sum(case when BIL_Status ='notcharged' then BIL_Rate else 0 end), 0) as notcharged
from ___BillableDatas
group by BIL_Date
答案 2 :(得分:0)
以下查询将每个日期返回一行:
php7.0-xml
由于select
BIL_Date,
sum((BIL_Status = 'charged') * BIL_Rate * BIL_Quantity) as charged,
sum((BIL_Status = 'notcharged') * BIL_Rate * BIL_Quantity) as notcharged
from ___BillableDatas
where BIL_BookingId = 21
group by BIL_Date
不在结果数组中,我假设您只需要在WHERE子句中定义的特定BookingId
的数据。
请注意,像BookingId
这样的表达式将返回(BIL_Status = 'charged')
表示TRUE,或1
表示MySQL中的FALSE。这样就可以避免长CASE语句。也不需要0
或COALESCE()
,因为IFNULL()
始终至少有一行具有非NULL值。
在PHP中执行查询后,您可以在获取数据的同时在一个循环中构建嵌套数组:
SUM()