左联接并获得最大日期时间值

时间:2019-06-10 07:31:48

标签: sql-server datetime left-join

我有两个表,

表1

        Id     Name
        ===========
        1      Name1
        2      Name2
        3      Name3

表2

        Id     Tb1Id   DateTime
        =======================
        1       1      20-09-2017
        2       1      01-09-2018
        3       2      01-09-2016
        4       2      02-09-2015 
        5       3      06-09-2016 
        6       3      10-09-2019

我想在Table1.Id = Table2.Tb1Id处加入这两个表,并从Table2获取最大日期时间值。结果应该是这样的。

        Id     Name     DateTime
        ========================
        1      Name1    01-09-2018
        2      Name2    01-09-2016
        3      Name3    10-09-2019

1 个答案:

答案 0 :(得分:2)

尝试一下

DECLARE @Table1 AS TABLE(Id INT,Name VARCHAR(20))
INSERT INTO @Table1
SELECT 1,'Name1' UNION ALL
SELECT 2,'Name2' UNION ALL
SELECT 3,'Name3' 

DECLARE @Table2 AS TABLE(Id INT, Tb1Id INT,[DateTime] DATETIME)
INSERT INTO @Table2       
SELECT 1,1,'2017-09-20' UNION ALL
SELECT 2,1,'2018-09-01' UNION ALL
SELECT 3,2,'2016-09-01' UNION ALL
SELECT 4,2,'2015-09-02' UNION ALL 
SELECT 5,3,'2016-09-06' UNION ALL 
SELECT 6,3,'2019-09-10' 

SELECT     t2.Tb1Id AS Id,
           t1.Name,
           MAX(t2.[DateTime]) AS [DateTime]
FROM @Table1 AS T1
INNER JOIN @Table2 AS t2
 ON T1.Id = t2.Tb1Id
GROUP BY 
     t2.Tb1Id,
     t1.Name

结果

Id  Name        DateTime
-----------------------------------
1   Name1   2018-09-01 00:00:00.000
2   Name2   2016-09-01 00:00:00.000
3   Name3   2019-09-10 00:00:00.000