与CTE一起使用时行号被破坏

时间:2018-06-18 14:53:37

标签: sql sql-server sql-cte

这是我的查询CTE里面的SQL工作正常,我希望每个城市名称前20行:

{{1}}

尽管主查询工作正常但上面的查询返回错误的行..

我在互联网上找不到任何解决方案

1 个答案:

答案 0 :(得分:2)

如果每个城市需要20行,那么cte中的row_number OVER子句应为

with taniCte as
(
  select sl.Adi as [CityName]
       , mt.ICD10Kodu as [Tanı]
       , count(mt.ICD10Kodu) as sayi
       , RowNum = ROW_NUMBER()OVER(partition By sl.Adi order by count(mt.ICD10Kodu)) -- this change in over clause
  from Muayene.Muayene mm with(nolock)
       join Muayene.Tani mt with(nolock) on mm.ID = mt.MuayeneId
       join Ortak.Kurum ok with(nolock) on mm.CreatedKurumKodu = ok.KurumKodu
       join Skrs.Il sl with(nolock) on ok.IlKodu = sl.Kodu
   group by sl.Adi, mt.ICD10Kodu 
   --order by [CityName], sayi desc // commentewhen its moved inside cte
)
select [CityName], [Tanı],sayi, RowNum 
from taniCte 
where RowNum <= 20 
order by [CityName], sayi desc