SQL - 选择NVARCHAR列时的最新最大日期

时间:2017-08-18 10:59:22

标签: sql date duplicates max

我想只选择数据库中的最新输入。

目前,即使我使用max

过滤,它总是会给我所有评论

查询的简化版本

SELECT 
    A.[Id],
    UD.[Name],
    MAX(CONVERT(DATE, AN.[PostedOn])) 'date',
    CAST(AN.[Content] AS NVARCHAR(MAX)) 'comment'
FROM 
    [dbo].[Account] A 
LEFT JOIN  
    [dbo].[UserData] UD ON A.[UserId] = UD.UserId
LEFT JOIN 
    [dbo].[Note] AN ON UD.[UserId] = AN.[CustomerID]
GROUP BY
    A.[Id], UD.[Name], CAST(AN.[Content] AS NVARCHAR(MAX))

当前结果

+---------+------------------------+------------+-------+
|id       |Name                    |Date        |Comment|
+---------+------------------------+------------+-------+
|01       |John                    |2017-08-15  |Blue   |
|01       |John                    |2017-07-10  |Green  |
|02       |Bob                     |2017-07-15  |Green  |
|02       |Bob                     |2017-06-05  |Red    |
|03       |Eric                    |2017-08-15  |Yellow |
|04       |Karl                    |2017-08-15  |NULL   |
|04       |Karl                    |2017-06-10  |Black  |
+---------+------------------------+------------+-------+

预期/期望的结果:

+---------+------------------------+------------+-------+
|id       |Name                    |Date        |Comment|
+---------+------------------------+------------+-------+
|01       |John                    |2017-08-15  |Blue   |
|02       |Bob                     |2017-07-15  |Green  |
|03       |Eric                    |2017-08-15  |Yellow |
|04       |Karl                    |2017-08-15  |NULL   |
+---------+------------------------+------------+-------+

仅供参考我如果从查询中删除CAST(AN.[Content] AS NVARCHAR(MAX)) 'comment',那么我就不会看到重复的问题。名称/身份不再(但没有评论)

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

使用ROW_NUMBER()

SELECT t.*
FROM (SELECT . . .,
             ROW_NUMBER() OVER (PARTITION BY A.id ORDER BY convert(date, AN.[PostedOn]) DESC) as seqnum
      FROM [dbo].[Account] A LEFT JOIN
           [dbo].[UserData] UD
           ON A.[UserId] = UD.UserId LEFT JOIN
           [dbo].[Note] AN
           ON UD.[UserId] = AN.[CustomerID]
     ) t
WHERE seqnum = 1;

. . .用于您想要的列列表。

注意:您的查询不是过滤最大值。您的查询使用聚合查询计算最大值。了解过滤和聚合之间的区别非常重要。

答案 1 :(得分:0)

SELECT
    t.id, t.Name, t.date, t.Comment
FROM
(
    SELECT A.id, UD.Name, CONVERT(date, AN.[PostedOn]) AS date, t.Comment,
        ROW_NUMBER() OVER (PARTITION by t.id
                           ORDER BY CONVERT(date, AN.[PostedOn]) DESC) rn
    FROM [dbo].[Account] A
    LEFT JOIN  [dbo].[UserData] UD
        ON A.[UserId] = UD.UserId
    LEFT JOIN [dbo].[Note] AN
        ON UD.[UserId] = AN.[CustomerID]
) t
WHERE t.rn = 1