简体   繁体   English

SQL获取每个组的最大值记录

[英]SQL Get records with max value for each group

I have 2 tables Journal and Users Journal looks like this:我有 2 个表 Journal 和 Users Journal 看起来像这样:

TransTime跨时 RegNumber注册号 UserID用户身份
5/26/2022 11:00:00 2022 年 5 月 26 日 11:00:00 101 101 3 3
5/26/2022 11:30:00 2022 年 5 月 26 日 11:30:00 102 102 2 2
5/26/2022 13:00:00 2022 年 5 月 26 日 13:00:00 101 101 5 5
5/26/2022 14:30:00 2022 年 5 月 26 日 14:30:00 103 103 4 4
5/26/2022 15:00:00 2022 年 5 月 26 日 15:00:00 102 102 1 1

Users table用户表

UserID用户身份 Name姓名
1 1 Ross罗斯
2 2 Rachel雷切尔
3 3 Chandler钱德勒
4 4 Monica莫妮卡
5 5 Joey乔伊

What I would like to do is get a table of the Registers and their most recent user names.我想做的是得到一个寄存器表和他们最近的用户名。 This should seem very simple.这看起来应该很简单。 But since I am joining tables on the userID, I am getting all 5 records on the first table.但由于我在 userID 上加入表,所以我在第一个表上获得了所有 5 条记录。 But it should look like this:但它应该看起来像这样:

RegNumber注册号 LastUser最后用户
101 101 Joey乔伊
102 102 Ross罗斯
103 103 Monica莫妮卡

I have tried a variety of solutions but haven't found the right one.我尝试了多种解决方案,但没有找到合适的解决方案。 Any help is appreciated.任何帮助表示赞赏。

if you start with an inner join of the max transtime per regNumber, then join with user table:如果您从每个 regNumber 的最大传输时间的内部连接开始,则使用用户表连接:

Select J.RegNumber, U.Name
From Journal J
Inner join 
(Select Max(TransTime) as TransTime, RegNumber 
From Journal
Group by RegNumber) J2 on J.TransTime = J2.TransTime and J.RegNumber = J2.RegNumber
Inner join
Users U on J.UserID = U.UserID

Here is an option using a CTE:这是使用 CTE 的选项:

;with cte as
(
    Select  RegNumber,
            UserID = max(UserID)
    From journal
    group by RegNumber
)
Select  RegNumber = C.RegNumber,
        LastUser = U.Name
From cte C
Join users U ON U.Userid = C.UserID
order by C.RegNumber

This answer is not, at its core, substantively different from the others.从本质上讲,这个答案与其他答案没有本质上的不同。 However, in terms of being helpful to the target audience it's more readable, more self-documenting, and more standard in terms of formatting.然而,就对目标受众有帮助而言,它更具可读性、更自文档化,并且在格式方面更标准。

Sidebar: This SQL takes the data design at face value, as a given, with the implicit assumption that TransTime is the PK or at least uniquely indexed, possibly in conjunction with RegNumber.侧边栏:此 SQL 将数据设计作为给定的表面价值,隐含假设 TransTime 是 PK 或至少是唯一索引的,可能与 RegNumber 结合使用。 Bottom line, it would be good to have a little more info about the key structure along with the original question.最重要的是,最好在原始问题的同时获得更多关于关键结构的信息。

WITH LatestEntries AS
(
    SELECT
        MAX(TransTime) AS LatestTimeForReg
        ,RegNumber
    FROM
        Journal
    GROUP BY
        RegNumber
)
SELECT
    J.RegNumber
    ,U.[Name] AS LastUser
FROM
    LatestEntries LE
    INNER JOIN Journal J ON LE.LatestTimeForReg = J.TransTime AND LE.RegNumber = J.RegNumber
    INNER JOIN Users U ON J.UserID = U.UserID
ORDER BY
    J.RegNumber
;

You can use a temptable or cte structure to rank your data based on RegNo and Trantime like below, then retrieve the most updated users for each journal:您可以使用temptablecte结构根据 RegNo 和 Trantime 对数据进行排名,如下所示,然后检索每个期刊的最新用户:

CREATE TABLE #Journals (TranTime DATETIME, RegNo INT, UserId INT)
CREATE TABLE #Users (UserId INT, UserName NVARCHAR(100))

INSERT INTO #Users VALUES(1,'Ross'),(2,'Rachel'),(3,'Chandler'),(4,'Monica'),(5,'Joey')

INSERT INTO #Journals VALUES ('5/26/2022 11:00:00',101,3),('5/26/2022 11:30:00',102,2),
('5/26/2022 13:00:00',101,5),('5/26/2022 14:00:00',103,4),('5/26/2022 15:00:00',102,1)
    
;WITH cte as (
        SELECT *,rn=ROW_NUMBER() OVER (PARTITION BY RegNo ORDER BY TranTime DESC)
        FROM #Journals
    )
SELECT RegNo, u.UserName
FROM cte
INNER JOIN #Users u ON u.UserId = cte.UserId
WHERE rn=1 --since sort by TranTime is descending, it'll give you the latest user for each specific RegNo
ORDER BY RegNo

Tested and it works on SQL Server 2016.经过测试,它可以在 SQL Server 2016 上运行。

select u.Name, j.* 
from journal j 
inner join ( 
    select max(TransTime) last_update, RegNumber 
    from journal 
    group by RegNumber 
) t1 
inner join j.RegNumber = t1.RegNumber 
   and t1.last_update = j.TransTime 
left join Users_Journal uj on j.UserID= uj.UserID

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

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