从子查询获取每组的最新记录

时间:2020-06-07 22:05:38

标签: sql-server sql-server-2008 subquery

我想从查询中为每个date获取基于email的最新记录。

此查询为每个电子邮件生成多个记录。我们将此输出称为表C

我的问题是:如何仅从别名表C中过滤最新记录。

+-------------------+-----+------------+
| email             | id  | date       |
+-------------------+-----+------------+
| hello@example.com | 123 | 2020-06-21 |
+-------------------+-----+------------+
| hello@example.com | 123 | 2020-06-15 |
+-------------------+-----+------------+

期望的结果是:

+-------------------+-----+------------+
| email             | id  | date       |
+-------------------+-----+------------+
| hello@example.com | 123 | 2020-06-21 |
+-------------------+-----+------------+

我的开始查询(产生多个电子邮件记录)如下:

SELECT DISTINCT
    Email,
    ID,
    Date
FROM [TABLE_A] AS a    
LEFT JOIN (
    select *
    from [TABLE_B]
    where ID = '123'
) AS b
ON a.Email = b.Key

我的尝试:

SELECT c.Email, c.ID, c.Date
FROM (
    SELECT DISTINCT
        Email,
        ID,
        Date
    FROM [TABLE_A] AS a   
    LEFT JOIN (
        select *
        from [TABLE_B]
        where ID = '123'
    ) AS b ON a.Email = b.Key   
) AS c    
INNER JOIN (
    SELECT Email, max(Date) as MaxDate
    FROM c
    GROUP BY Email
) tm on c.Email = tm.Email and c.Date = tm.Date

像SQL一样,由于出现错误,我无法“看到”表C:

无效的对象名称

1 个答案:

答案 0 :(得分:0)

您可以将WITH TIESrow_number()配合使用

示例

Select Top 1 with ties *
 From  YourTable
 Order By Row_Number() over (Partition By Id Order By [Date] Desc)
相关问题