SQL Server中Union分组查询结果不符合预期的问题
Fixing GROUP BY + UNION Query to Show Aggregates in Single Row per League
你的问题出在UNION的使用逻辑上——它是把两个结果集纵向拼接,导致同一个联赛(league)的两组统计值被拆成了两行,还没法直接区分列的含义,同时漏掉了像league 2这种没有对应数据时的0值展示。
先拆解下你的原查询问题:
select league , count(*) as total_1 from Games where score_away is not null and score_home is not null group by League union select league , count(*) as total_2 from Games where score_away is null and score_home is null group by League
UNION会沿用第一个查询的列名,所以你看到的结果里只有total1列;而且它只会返回存在匹配数据的行,没法自动补全0值。
正确解决方案:用条件聚合实现一行多统计
只需要一次GROUP BY,配合CASE WHEN在聚合函数里做条件判断,就能直接得到你想要的结构:
select league, count(case when score_away is not null and score_home is not null then 1 end) as total_1, count(case when score_away is null and score_home is null then 1 end) as total_2 from Games group by league
逻辑解释
count(case ... then 1 end):当满足条件时返回1,不满足时返回NULL,而COUNT函数会自动忽略NULL值,最终统计的就是符合条件的行数。- 因为是对全表按league分组,即使某个league没有符合第二个条件的数据,
total_2也会返回0(没有符合条件的行时,COUNT结果自然为0)。
用你的测试数据验证:
- league 1:满足total_1的有3场,满足total_2的有2场 → 对应结果
1 | 3 | 2 - league 2:满足total_1的有3场,无满足total_2的比赛 → 对应结果
2 | 3 | 0
完全匹配你的期望输出。
内容的提问来源于stack exchange,提问作者user7052482
相关产品推荐
相关产品推荐

