joined two queries with union all returned single value only?

i have merge two queries from where its returning 3 columns (month, count, targets) by executing both queries separately it returns me 2 records which is correct. but with UNION ALL its return me only single value:

My Query:

select s.month,COALESCE(max(s.count), NULL, 0) as count, COALESCE(max(s.targets), NULL, 0) as target from 
(SELECT MONTHNAME(tm.meeting_date) as month, count(DISTINCT tm.meeting_id) as count, NULL as targets 
FROM tig as t 
left join tig_meeting as tm ON t.tig_code = tm.tig_code 
WHERE tm.meeting_date IS NOT NULL AND tm.meeting_date != 0 AND t.school_district = 'Islamabad C3' 
AND (tm.meeting_date BETWEEN "2018-07-01" AND "2018-09-30") AND tm.key_support <> 'QuarterlyTigMeetings' AND tm.key_support <> 'QTIG_by_SSA' 
AND tm.key_support <> 'MTIG_by_SSA' AND tm.meeting_no NOT LIKE '%RF' 
GROUP BY MONTH(tm.meeting_date) 
UNION ALL 
SELECT mpt.month, NULL as count, SUM(mpt.monthly_target) as targets 
FROM meeting_plan_targets mpt 
LEFT JOIN meeting_plans mp ON mp.id = mpt.meeting_plan_id 
WHERE mp.district = 'Islamabad C3' AND mp.module_title = 1 AND mp.year = 2018 AND mp.quarter = "Quarter 4" GROUP BY mpt.month) s 
group by MONTH(s.month)

for reference please check attached image

enter image description here

2 answers

  • answered 2018-11-08 05:59 fa06

    You can try below

    select s.`month`,COALESCE(max(s.count),0) as count, COALESCE(max(s.targets),0) as target from 
    (
    SELECT MONTHNAME(tm.meeting_date) as `month`,MONTH(tm.meeting_date) as monnum,count(DISTINCT tm.meeting_id) as count, NULL as targets 
    FROM tig as t 
    left join tig_meeting as tm ON t.tig_code = tm.tig_code 
    WHERE tm.meeting_date IS NOT NULL AND tm.meeting_date != 0 AND t.school_district = 'Islamabad C3' 
    AND (tm.meeting_date BETWEEN '2018-07-01' AND '2018-09-30') AND tm.key_support <> 'QuarterlyTigMeetings' AND tm.key_support <> 'QTIG_by_SSA' 
    AND tm.key_support <> 'MTIG_by_SSA' AND tm.meeting_no NOT LIKE '%RF' 
    GROUP BY MONTHNAME(tm.meeting_date),MONTH(tm.meeting_date)
    
    UNION ALL 
    
    SELECT MONTHNAME(mpt.month), MONTH(mpt.month),NULL as count, SUM(mpt.monthly_target) as targets 
    FROM meeting_plan_targets mpt 
    LEFT JOIN meeting_plans mp ON mp.id = mpt.meeting_plan_id 
    WHERE mp.district = 'Islamabad C3' AND mp.module_title = 1 AND mp.year = 2018 AND mp.quarter = 'Quarter 4' 
    GROUP BY MONTHNAME(mpt.month),MONTH(mpt.month)
    ) s 
    group by s.`month`,monnum order by monnum
    

  • answered 2018-11-08 05:59 Barmar

    s.month is a month name. MONTH(s.month) won't work, because the MONTH() function expects its argument to be a date or datetime (or a string that can be parsed as a date or datetime), not a month name.

    Use GROUP BY s.month instead.