Sql 是否有更好的解决方案连接同一数据集以获得用于聚合的维度的不同计数?
我必须对某些度量值进行聚合,但我还必须说明一个维度有多少不同的值,我使用这些值进行聚合。我可以使用两个子选项解决问题,但性能不是最好的。有没有办法只用一个选择来解决这个问题?欢迎任何性能更好的解决方案 我拥有的测试数据:Sql 是否有更好的解决方案连接同一数据集以获得用于聚合的维度的不同计数?,sql,postgresql,Sql,Postgresql,我必须对某些度量值进行聚合,但我还必须说明一个维度有多少不同的值,我使用这些值进行聚合。我可以使用两个子选项解决问题,但性能不是最好的。有没有办法只用一个选择来解决这个问题?欢迎任何性能更好的解决方案 我拥有的测试数据: create table test ( dim1 varchar(50), dim2 varchar(50), measure1 numeric, measure2 numeric ) insert into test select 'a','sas',120,1700 un
create table test
(
dim1 varchar(50),
dim2 varchar(50),
measure1 numeric,
measure2 numeric
)
insert into test
select 'a','sas',120,1700
union all
select 'b','pop',150,150,
union all
select 'c','sas',132,150,
union all
select 'c','sas',150,100
我有:
select x.dim1,
x.dim2,
y.count_dim2
x.measure1,
x.measure2
from
(
select
dim1,
dim2,
sum(measure1) measure1,
sum(measure2) measure2
from test
group by dim1, dim2
) x,
(
select
x.dim1,
count(distinct dim2) as count_dim2
from test
group by dim1
) y
where x.dim1 = y.dim1
是否有任何方法可以使用1 select only解决上述问题?您只需根据聚合结果进行组计数即可:
SELECT
dim1,
dim2,
COUNT(*) OVER (PARTITION BY dim1),
SUM(measure1) measure1,
SUM(measure2) measure2
FROM test
GROUP BY dim1, dim2