如何使用月份名称获取最近 3 个月的计数,如果该月份没有记录需要使用月份名称获取 0 [重复]
Posted
技术标签:
【中文标题】如何使用月份名称获取最近 3 个月的计数,如果该月份没有记录需要使用月份名称获取 0 [重复]【英文标题】:How to get the counts of last 3 months with month names, if no record for that month need to get 0 with month name [duplicate] 【发布时间】:2019-01-01 07:10:33 【问题描述】:我想从当前日期获取最近 3 个月的数据,然后我将获得四个月的名称,因为我只有 3 个月的数据,但中间没有一个月的数据。
SELECT
count(v.visit_id) as count,
MONTHNAME(v.updated) AS Month_name
FROM patient_status as p, visit_history_details as v
WHERE v.visit_id = p.visit_id and v.hospital_code = 'id'
and p.doctor_id = '2' and v.updated >= now()-interval 3 month
GROUP by Month_name
我的结果是这样的:
January 10
December 12
October 10
但我想要这个结果:
January 10
December 12
November 0
October 10
请帮我解决这个问题
【问题讨论】:
能否提供您的样本数据 【参考方案1】:对于月份,您应该使用子查询来获取您需要的所有月份
select monthname(my_date), ifnull(count, 0)
from (
select str_to_date('2018-01-01', '%Y-%m-%d') as my_date
union
select str_to_date('2018-10-01', '%Y-%m-%d')
union
select str_to_date('2018-11-01', '%Y-%m-%d')
union
select str_to_date('2018-12-01', '%Y-%m-%d')
) t
left join (
SELECT
count(v.visit_id) as count,
MONTHNAME(v.updated) AS Month_name,
MONTH(v.updated) as my_month
FROM patient_status as p
INNER JOIN visit_history_details as v
ON v.visit_id = p.visit_id
WHERE v.hospital_code = 'id'
and p.doctor_id = '2'
and v.updated >= now()-interval 3 month
GROUP by Month_name
) r on r.my_month = t.my_month
你应该避免旧的隐式连接sintax并使用显式sintax
或者按照 Salman A 建议的更通用的解决方案
select monthname(my_date), ifnull(count, 0)
from (
select LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL 1 MONTH as my_date
union
select LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL 2 MONTH
union
select LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL 3 MONTH
union
select LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL 4 MONTH
) t
left join (
SELECT
count(v.visit_id) as count,
MONTHNAME(v.updated) AS Month_name,
MONTH(v.updated) as my_month
FROM patient_status as p
INNER JOIN visit_history_details as v
ON v.visit_id = p.visit_id
WHERE v.hospital_code = 'id'
and p.doctor_id = '2'
and v.updated >= now()-interval 3 month
WHERE v.visit_id = p.visit_id and v.hospital_code = 'id'
and p.doctor_id = '2' and v.updated >= now()-interval 3 month
GROUP by Month_name
【讨论】:
@TimBiegeleisen ..非常感谢..(错误的复制和粘贴。)新年快乐.. 您可以将硬编码日期替换为LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL n MONTH
@SalmanA 。正确.. asnwer 更新。也有你的建议以上是关于如何使用月份名称获取最近 3 个月的计数,如果该月份没有记录需要使用月份名称获取 0 [重复]的主要内容,如果未能解决你的问题,请参考以下文章