3

I want get the last 3 months data from current date then i will get four month names in that i have only 3 month data but i do not have one month data in middle.

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

My Result are coming like this:

January  10 
December 12
October  10

But I want this result:

January  10 
December 12
November 0 
October  10

please help me how to solve this issue

Shadow
  • 33,525
  • 10
  • 51
  • 64
saiibitta
  • 377
  • 2
  • 18

1 Answers1

3

For the month you should use a subquery for get all the month you need:

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

And you should avoid old implicit join syntax and use the explicit syntax.

Or as suggested by Salman A for a more general solution:

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
halfer
  • 19,824
  • 17
  • 99
  • 186
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107