使用union连接两个查询,所有查询只返回一个值?

5n0oy7gb  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(369)

我合并了两个查询,其中返回3列(月、计数、目标),通过分别执行这两个查询,它将返回2条记录,这是正确的。但所有的联合只会给我一个值:
我的问题:

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)

参考请检查所附图片

tp5buhyn

tp5buhyn1#

你可以在下面试试

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
o75abkj4

o75abkj42#

s.month 是月份名称。 MONTH(s.month) 行不通,因为 MONTH() 函数要求其参数是日期或日期时间(或可以解析为日期或日期时间的字符串),而不是月份名称。
使用 GROUP BY s.month 相反。

相关问题