是否有更好的方法根据不同的标准计算id的行?
例如,我有一个包含列的表:
id, state, city
我的查询:
select
ID, city, state, UScount, statecount, citycount
from
(select count(*) USCount, ID
from table
group by ID) UScount
inner join
(select count(*) stateCount, ID
from table
group by ID, state) statecount on UScount.ID = Statecount.ID
inner join
(select count(*) cityCount, ID
from table
group by ID, city) citycount on UScount.ID = citycount.ID
我只是想清理它,因为实际上我有大约20种不同的数量并且看起来不太好
答案 0 :(得分:5)
您在寻找窗口功能吗?
select t.*,
count(*) over () as cnt,
count(*) over (partition by state) as cnt_state,
count(*) over (partition by state, city) as cnt_state_city
from table t;
我不确定id
是否应该成为partition by
的一部分。