通过并集加入两个查询,都仅返回单个值?

时间:2018-11-08 05:51:25

标签: mysql union union-all

我合并了两个查询,查询从中返回3列(月份,计数,目标) 通过分别执行两个查询,它返回2条正确的记录。 但是使用UNION ALL,它只返回一个值:

我的查询

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)

作为参考,请检查附件图像

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以在下面尝试

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

答案 1 :(得分:0)

s.month是月份名称。 MONTH(s.month)不起作用,因为MONTH()函数期望其参数为日期或日期时间(或可解析为日期或日期时间的字符串),而不是月份名称。

改为使用GROUP BY s.month