我有描述和创建日期的合格风险,谁附加到风险子类别,最后一个风险属于风险类别,每个风险都有一个名称,如风险1' ,我的目标是按过去3个月的名称和风险类别计算风险数量。
我有这个sql请求:
SELECT MONTH(risk.creation_date) as month, count(*) as number, risk_category.name as risk_name FROM risk As risk
JOIN risk_subcategory on risk_subcategory.id = risk.risk_subcategory_id
JOIN risk_category on risk_category.id = risk_subcategory.risk_category_id
where risk.creation_date >= (NOW()-INTERVAL 3 MONTH) GROUP BY MONTH(risk.creation_date), risk_category.name;
返回此结果集:
month number risk_name
---------------------------
12 1 Risk 1
12 3 Risk 2
1 1 Risk 3
1 9 Risk 2
2 1 Risk 3
2 1 Risk 1
2 10 Risk 2
我想要这个结果(包括0):
month number risk_name
---------------------------
12 1 Risk 1
12 3 Risk 2
12 0 Risk 3
1 0 Risk 1
1 1 Risk 3
1 9 Risk 2
2 1 Risk 3
2 1 Risk 1
2 10 Risk 2
我该怎么办? 感谢
答案 0 :(得分:3)
您正在从执行count
的同一个表中选择月份,因此如果月份x的计数应该为0,则意味着没有包含month = x的行。你无法从那张桌子上获得那个月,因为它根本就不存在。
如果您希望获得所有月份,则应使用另一个表格,其中包含所有可用月份,并在该表格与left join
之间执行risk
,例如
select t1.month, coalesce(t2.count(*), 0)), t2.risk_name
from months t1
left join
risk t2
on t1.month = MONTH(risk.creation_date)
group by t1.month, t2.risk_name
答案 1 :(得分:0)
根据投票的答案,我试过这个但是没有用:
SELECT MONTH(risk.creation_date) as month, count(*) as number, risk_category.name as risk_name FROM risk As risk
JOIN risk_subcategory on risk_subcategory.id = risk.risk_subcategory_id
JOIN risk_category on risk_category.id = risk_subcategory.risk_category_id
LEFT JOIN (
SELECT mois
FROM
(
SELECT 1 AS mois
UNION SELECT 2 AS mois
UNION SELECT 3 AS mois
UNION SELECT 4 AS mois
UNION SELECT 5 AS mois
UNION SELECT 6 AS mois
UNION SELECT 7 AS mois
UNION SELECT 8 AS mois
UNION SELECT 9 AS mois
UNION SELECT 10 AS mois
UNION SELECT 11 AS mois
UNION SELECT 12 AS mois
) as year
) as months on months.mois = MONTH(risk.creation_date)
where risk.creation_date >= (NOW()-INTERVAL 3 MONTH) GROUP BY MONTH(risk.creation_date), risk_category.name;