基于每个州,我需要获得与该州相关的总rxnumber。
我尝试了我的语法,但它没有选择与状态相关联的Max(RxNumber)。
with cte as
(
select [State],
RxNumber,
ROW_NUMBER() OVER(PARTITION BY [State]
ORDER BY [RxNumber] Desc) as [RowCount]
from dbo.RxNumberState
)
select [State], MAX([RowCount]) as [TotalRx]
from cte
Group By [State],[RxNumber]
答案 0 :(得分:2)
您需要从RXNUMBER
子句中删除GROUP BY
试试这个......
with cte as
(
select [State],
RxNumber
,ROW_NUMBER() OVER(PARTITION BY [State] ORDER BY [RxNumber] Desc) as [RowCount]
from
dbo.RxNumberState
)
select [State]
,MAX([RowCount]) as [TotalRx]
, MAX(RXNUMBER) MAX_RXNUMBER
from cte
Group By [State]
更好的方法是写下这个,应该解决你的目的
select [State]
, COUNT(RXNUMBER) as [TotalRx]
, MAX(RXNUMBER) MAX_RXNUMBER
from dbo.RxNumberState
Group By [State]
如果同一RXNUMBER
有多个条目,请使用COUNT(DISTINCT RXNUMBER)
答案 1 :(得分:0)
未经测试但应该给你一些想法:
with cte as
(
select distinct [State],
rank() OVER(partition by [State] order by [State]) as [StateNumber]
from dbo.RxNumberState
group by [State]
)
select
r.[State],
count(*) as [TotalRx]
from dbo.rxNumberState r
join cte c on c.[State] = r.[State]
Group By r.[State]