You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将UNION查询结果中的每组合并为单行?

如何将UNION查询结果中的每组合并为单行?

示例数据

idusernamegroupunitdepartmentteamstatus
1user1g1u1d1t1active
2user2g1u1d1t2active
3user3g1u1d1t3inactive
4user4g3u6d12t30active
5user5g25u54d70t88inactive

原分组统计查询

SELECT group
     , unit
     , department
     , NULL as team
     , COUNT(*) AS count
  FROM table
 WHERE group='g1' 
   AND unit='u1' 
   AND department='d1'
GROUP
    BY group
     , unit
     , department
UNION ALL
SELECT group
     , unit
     , department
     , team
     , COUNT(*) AS count
  FROM table
 WHERE group='g25' 
   AND unit='u54' 
   AND department='d70' 
   AND team='t88'
GROUP
    BY group
     , unit
     , department
     , team

原查询返回结果

groupunitdepartmentteamstatuscount
g1u1d1NULLactive2
g1u1d1NULLinactive1
g25u54d70t88active0
g25u54d70t88inactive1

期望的合并后结果

groupunitdepartmentteamactive_countinactive_count
g1u1d1NULL21
g25u54d70t8801

解决方案:使用条件聚合实现单行合并

核心思路是用条件聚合替代原查询中按状态拆分的逻辑,通过CASE语句筛选指定状态后计数,直接将同一分组的两种状态统计结果输出到单行。

针对示例的优化查询

SELECT group
     , unit
     , department
     , NULL as team
     , COUNT(CASE WHEN status = 'active' THEN 1 END) AS active_count
     , COUNT(CASE WHEN status = 'inactive' THEN 1 END) AS inactive_count
  FROM table
 WHERE group='g1' 
   AND unit='u1' 
   AND department='d1'
GROUP BY group, unit, department
UNION ALL
SELECT group
     , unit
     , department
     , team
     , COUNT(CASE WHEN status = 'active' THEN 1 END) AS active_count
     , COUNT(CASE WHEN status = 'inactive' THEN 1 END) AS inactive_count
  FROM table
 WHERE group='g25' 
   AND unit='u54' 
   AND department='d70' 
   AND team='t88'
GROUP BY group, unit, department, team

动态构建查询的示例

若需根据输入数组(如["g1", "u1", "d1"]、["g25", "u54", "d70", "t88"]、["g3", "u6"])动态生成查询,需按数组包含的层级字段构建SELECT、WHERE和GROUP BY子句,示例如下:

SELECT group_
     , unit
     , department
     , NULL as team
     , COUNT(CASE WHEN status='active' THEN 1 END) AS active_count
     , COUNT(CASE WHEN status='inactive' THEN 1 END) AS inactive_count
  FROM my_table
 WHERE group_='g1' 
   AND unit='u1' 
   AND department='d1'
GROUP BY group_, unit, department
UNION ALL
SELECT group_
     , unit
     , department
     , team
     , COUNT(CASE WHEN status='active' THEN 1 END) AS active_count
     , COUNT(CASE WHEN status='inactive' THEN 1 END) AS inactive_count
  FROM my_table
 WHERE group_='g25' 
   AND unit='u54' 
   AND department='d70' 
   AND team='t88'
GROUP BY group_, unit, department, team
UNION ALL
SELECT group_
     , unit
     , NULL as department
     , NULL as team
     , COUNT(CASE WHEN status='active' THEN 1 END) AS active_count
     , COUNT(CASE WHEN status='inactive' THEN 1 END) AS inactive_count
  FROM my_table
 WHERE group_='g3' 
   AND unit='u6' 
GROUP BY group_, unit

内容的提问来源于stack exchange,提问作者pileup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 08:50:39