我正在寻找一种SQL编码,该编码将在某个状态出现时对计数求和,并对该状态的特定行具有该总和。我能够创建两列来总计特定状态的计数,但是每一行中都有这个数字。
例如,如果有24条亚利桑那记录,那么我去了24条记录,在亚利桑那的每一行中都出现。如果俄勒冈州有58条记录,那么我希望58条记录在俄勒冈州的每一行中。等等...
这是我目前拥有的
select appid, rcvddt, state,
sum(count(case when state = 'OR' then 1 else null end)) over () as ORcount,
sum(count(case when state = 'AZ' then 1 else null end)) over () as AZcount
from smbus.submissions
where (apprcvddt >= '2017-08-01' and apprcvddt <= '2018-08-31')
group by state, rcvddt, appid
order by (case when state is null then 1 else 0 end), state
答案 0 :(得分:1)
我认为您只想将count()
作为窗口函数:
select s.*,
count(*) over (partition by state) as state_cnt
from smbus.submissions s
where apprcvddt >= '2017-08-01' and apprcvddt <= '2018-08-31'
order by (case when state is null then 1 else 0 end), state