如何获得最后的记录?

时间:2017-10-06 05:26:04

标签: sql sql-server greatest-n-per-group

我有一个包含以下架构的表 TableReassignment

Id
StepId
FromUserId
ToUserId

TableReassignment的示例数据:特定步骤可能有也可能没有任何记录

1 , Step1 , UserA, UserB 
2 , Step1 , UserB, UserC 
3 , Step1 , UserC, UserD 
4 , Step1 , UserD, UserE 
5 , Step1 , UserF, UserG 
6 , Step2 , UserB, UserC 
7 , Step2 , UserC, UserD 
8 , Step2 , UserE, Userf 

还有用户表

UserId
UserName

还有StepUserDetails

StepId,
StepUserId

StepUserDetails的示例数据:

Step1, UserA
Step2, UserB
Step3, UserC
Step4, UserD

我的要求是,我想要StepUserDetails与现有的StepUsers,如果他们被重新分配,那么最后重新分配的用户。

预期输出应该像

Step1, UserG
Step2, UserF
Step3, UserC
Step4, UserD

2 个答案:

答案 0 :(得分:1)

您可以使用子查询

  select ToUserId
  from my_table where Id =(
  select max(Id)
  from my_table 
  where stepId='Step1'
  )

或加入

  select ToUserID
  from my_table 
  inner Join (
        select StepId, max(Id) my_id
        from my_table 
        group by StepId
  ) t on t.my_id = my_table.Id  and StepId  ='Step1'

以及您的更新问题

  select a.StepID, a.ToUserID
  from my_table  a
  inner Join (
        select StepId, max(Id) my_id
        from my_table 
        group by StepId
  ) t on t.my_id = a.Id  

答案 1 :(得分:1)

您可以使用以下查询:

WITH ReassignmentCTE AS (
   SELECT StepId, ToUserId, 
          ROW_NUMBER() OVER(PARTITION BY stepId ORDER BY Id DESC) AS rn
   FROM Reassignment
)    
SELECT s.StepId, COALESCE(c.ToUserId, s.StepUserId) AS StepUserId
FROM StepUserDetails AS s
LEFT JOIN ReassignmentCTE AS c ON s.StepId = c.StepId AND c.rn = 1

Demo here