简体   繁体   English

T-SQL查询以获取具有多个聚合函数的行

[英]T-SQL query to fetch row with multiple aggregate functions

I have the following problem. 我有以下问题。 I need to fetch the row for each distinct user_id with the min rank, max end date, max begin date, and max sequence number in that order . 我需要读取该行与最小级别,最大结束日期每个不同的USER_ID,最大开始日期和最大序列号的顺序 Essentially, I want a user's highest ranked, most recent MAJOR_ID . 从本质上讲,我想要用户排名最高的,最近的MAJOR_ID I am trying to avoid making separate temp tables and joining on those aggregate functions like the following: 我试图避免制作单独的临时表并加入这些聚合函数,如下所示:

select USER_ID
    , SEQ_NBR
    , BEGIN_DATE
    , END_DATE
    , MAJOR_RANK
    , MAJOR_ID
    , DEGREE_CODE
into #major0
from majors

select USER_ID
    , MIN(MAJOR_RANK) as MAJOR_RANK
into #major1
from #major0
group by USER_ID

select #major0.USER_ID
    , #major0.MAJOR_RANK
    , MAX(#major0.END_DATE) as END_DATE
into #major2
from #major0
inner join #major1 on #major0.USER_ID = #major1.USER_ID and #major0.MAJOR_RANK = #major1.MAJOR_RANK
group by #major0.USER_ID
    , #major0.MAJOR_RANK

etc... 等等...

until I get to that row that satisfies all the criteria, and I join back on all the fields from the original query. 直到我到达满足所有条件的那一行,然后我重新加入原始查询中的所有字段。 Does that make sense? 那有意义吗? It's a lot of work to write this out, and I can't create a view of it unless I made a absurdly long set of subqueries, I don't think I can utilize MIN(MAJOR_RANK) OVER (PARTITION BY USER_ID) in a subquery for all these fields because I will lose records that don't satisfy all of them. 写出这个是很多工作,除非我做了一个荒谬的MIN(MAJOR_RANK) OVER (PARTITION BY USER_ID)查询,否则我无法创建它的视图,我认为我不能在一个子查询中使用MIN(MAJOR_RANK) OVER (PARTITION BY USER_ID)所有这些字段的子查询,因为我将丢失不满足所有这些字段的记录。

Any suggestions would help! 任何建议都会有帮助! Thank you! 谢谢!

I do not see what the sequence_number is, but you can most likely solve this using a common table expression with row_number() 我没有看到sequence_number是什么,但你最有可能使用row_number()公用表表达式来解决这个问题。

;with cte as (
  select 
      user_id
    , begin_date
    , end_date
    , major_rank
    , major_id
    , degree_code
    , rn = row_number() over (
        partition by user_id 
        order by major_rank asc, end_date desc, begin_date desc /*, sequence_number? desc*/
        )
from majors
)
select 
    user_id
  , begin_date
  , end_date
  , major_rank
  , major_id
  , degree_code
from cte
where rn = 1

without the cte 没有cte

select 
    user_id
  , begin_date
  , end_date
  , major_rank
  , major_id
  , degree_code
from (
  select 
      user_id
    , begin_date
    , end_date
    , major_rank
    , major_id
    , degree_code
    , rn = row_number() over (
        partition by user_id 
        order by major_rank asc, end_date desc, begin_date desc /*, sequence_number? desc*/
        ) 
from majors
) sub
where rn = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM