我有以下MySQL查询:
SELECT Date,
Fail/(Success + Fail + NA) AS 'Rate'
FROM (
SELECT CAST( s.date_str AS DATE ) AS 'Date',
SUM(CASE WHEN k.result = 'SUCCESS' THEN 1 ELSE 0 END) Success,
SUM(CASE WHEN k.result = 'FAIL' THEN 1 ELSE 0 END) Fail,
SUM(CASE WHEN k.result != 'FAIL' AND k.result != 'SUCCESS' THEN 1 ELSE 0 END) NA
FROM Session s, KPI k
WHERE s.id = k.session_id
GROUP BY Date
)subQuery
它显示了这个结果,例如:
日期|率
.....................
2015-10-15 | 0.0836
2015-10-16 | 0.0279
2015-10-19 | 0.1569
2015-10-21 | 0.2756
所以它只显示有些数据时的结果.. 我想要实现的是,当没有数据显示下一个日期并且费率为0.0000时,所以在该示例中它看起来像这样:
日期|率
.....................
2015-10-15 | 0.0836
2015-10-16 | 0.0279
2015-10-17 | 0.0000
2015-10-18 | 0.0000
2015-10-19 | 0.1569
2015-10-20 | 0.0000
2015-10-21 | 0.2756
我怎么能实现这个目标?
答案 0 :(得分:2)
您需要加入另一个至少有30行的表来制作数据集中不存在的任何日期。类似的东西:
Session
将 select * from(
select curdate() - interval @rn := @rn + 1 day as last_30_date
from table_with_at_least_30_rows
join (select @rn := -1) rows limit 30
) days
left join (select curdate() as data_date) d on last_30_date = data_date;
替换为您的查询。