如何将多条COUNT查询合并为单条SQL语句获取多统计列
合并多个统计查询为单条SQL语句
你需要从fruit表一次性获取三个统计值:总条目数、红色水果数量、纽约地区的红色水果数量,原来的三条独立SQL可以通过条件聚合合并成单条语句,你之前尝试的写法存在语法错误,正确的实现方式如下:
正确SQL语句
select count(*) as total_items, count(case when color = 'red' then 1 end) as red_items, count(case when color = 'red' and substring(city, 1, 8) = 'New York' then 1 end) as fruit_in_newyork from fruit;
或者用SUM函数实现(效果一致):
select count(*) as total_items, sum(case when color = 'red' then 1 else 0 end) as red_items, sum(case when color = 'red' and substring(city, 1, 8) = 'New York' then 1 else 0 end) as fruit_in_newyork from fruit;
原理说明
count(*)直接统计表中所有条目数,对应total_items;- 条件聚合通过
case when判断每行是否符合统计条件:符合则返回1(或非null值),不符合则返回null(或0),再用count或sum汇总得到目标统计值; substring(city, 1, 8) = 'New York'用来匹配城市名称前8位为"New York"的记录,保持和你原查询的逻辑一致。
内容的提问来源于stack exchange,提问作者Makiyo
相关产品推荐
相关产品推荐

