如何获取最近3个月带有月份名称的计数,如果该月没有记录需要获得带有月份名称的0

时间:2019-01-01 07:10:33

标签: mysql

我想从当前日期获取最近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 个答案:

答案 0 :(得分:3)

对于月份,您应该使用子查询来获取所需的全部月份

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