繁体   English   中英

如何通过一个 SQL 查询获得不同的计数?

[英]How to get different counts with one SQL query?

我知道这个实际的语法是假的,但它会帮助你理解我想要什么。 我需要这种格式,因为它是更大查询的一部分。

select location,
       count(*) as tot_proj where project_status='live',
       sum(fte_count) as tot_emp where project_status='live' and fte_count != 'NULL'
from table_name 
group by location

我想在一个查询中完成所有这些...我试过这个

select count(*) as tot_proj,
       "location" ,
       sum(fte_count::float) as ft
 from insights_view iv2 
 where project_status = 'Live' and fte_count != 'NULL'
 group by "location"

但我的 tot_proj 计数不匹配...

我认为您需要以下语法:

select location,
       count(*) filter(where project_status = 'live') as tot_proj ,
       sum(fte_count) filter(where project_status = 'live') as tot_emp 
from table_name 
group by location

这使用 Postgres 支持的标准filter子句来聚合函数。 您不需要检查fte_count是否为null ,因为sum()忽略null值(如果必须,您需要is not null!= 'NULL'

另一方面,如果您运行的是 MySQL 而不是 Postgres:

select location,
       sum(project_status = 'live') as tot_proj ,
       sum(case when project_status = 'live' then fte_count end) as tot_emp 
from table_name 
group by location

我会将'live'比较移至where子句。 然后,如果您真的是指NULL而不是'NULL' ,您可以将这些值相加。 所以:

select location, count(*) as tot_proj , sum(fte_count) as tot_emp 
from table_name 
where project_status = 'live'
group by location;

请注意, 'NULL'是一个字符串。 在字符串上使用sum()没有意义,所以我猜你的意思是NULL SQL 关键字。 如果是这样,该值将被sum()和大多数其他聚合函数忽略。

此外,上面将过滤掉任何没有“实时”项目的location 因为您提出了一个带有where过滤器的版本,所以我猜这不是问题。

select location,
       sum(project_status='live') as tot_proj,
       sum(case when project_status='live' then fte_count end) as tot_emp 
from table_name 
group by location

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM