如何在 SQL 视图中将计数和总和组表示为列?
Posted
技术标签:
【中文标题】如何在 SQL 视图中将计数和总和组表示为列?【英文标题】:How to represent groups of counts and sums as columns in a SQL view? 【发布时间】:2019-01-17 12:22:27 【问题描述】:基本上我在 Postgresql 中定义了 mytable
id integer,
ownername text,
length integer,
status integer
预期结果是创建一个视图,该视图将为每个所有者名称行包含以下列
ownername | count_in_status1 | sum_length_status1 | count_in_status2 | sum_length_status2 | count_in_status3 | sum_length_status3 | ..... | total_count | total_sum_length
这有点难以解释,但基本上我需要每个所有者名称的计数和总和,最后是总计数和总长度。目前实际上有5种状态
尝试了以下
create view myview as
select ownername, status, count(*), sum(length) from mytable group by ownername, status
这会返回数据,但不是以我上面介绍的最有效的方式。如何实现?
【问题讨论】:
【参考方案1】:我想这就是你想要的:
create view myview as
select ownername,
count(*) filter (where status = 1) as cnt_status_1,
sum(length) filter (where status = 1) as len_status_1,
count(*) filter (where status = 2) as cnt_status_2,
sum(length) filter (where status = 2) as len_status_2,
. . . -- continue for each status
count(*) as cnt,
sum(length) as length
from mytable
group by ownername;
【讨论】:
你不需要状态栏。 @a_horse_with_no_name 。 . .谢谢。【参考方案2】:使用Filter
是一个优雅的解决方案(请参阅@Gordon Linoff 回复)
兼容很多数据库,yan也可以写:
create view myview as
select ownername,
sum(case when status = 1 then 1 else 0 end) as cnt_status_1,
sum(case when status = 1 then length else 0 end) as len_status_1,
sum(case when status = 1 then 1 else 0 end) as cnt_status_2,
sum(case when status = 1 then length else 0 end) as len_status_2,
. . . -- continue for each status
count(*) as cnt,
sum(length) as length
from mytable
group by ownername;
【讨论】:
其实filter()
是标准的ISO SQL以上是关于如何在 SQL 视图中将计数和总和组表示为列?的主要内容,如果未能解决你的问题,请参考以下文章