首页 > 解决方案 > 查询给出了期望的结果,但希望使用此逻辑在案例表达式中应用窗口函数

问题描述

寻找更好的解决方案,我写的这个查询对我有用,我想知道是否有更好的方法或相同的逻辑可以在案例表达式中使用。

我已经编写了一个查询,该查询使用窗口函数给出了各个季度的每个 id 的最大计数,然后拉取 1 的 seqnum 并给出结果。

我想知道是否可以在具有相似逻辑的案例表达式中使用相同的查询

select id,Quarter_yr, country
from (select id,Quarter_yr, country, count(*) as cnt,
             row_number() over (partition by id, Quarter_yr order by count(*) desc) as seqnum
      from  table 
      group by id,Quarter_yr,country
     ) t
where seqnum = 1;

标签: sqlsql-servertsqlcase

解决方案


也许这个查询就是你要找的

select top(1) id, Quarter_yr, country, count(*) as cnt
from table 
group by id, Quarter_yr, country
order by count(*) desc;

推荐阅读