如何获取每个用户名的最新记录

时间:2018-10-10 08:22:54

标签: sql-server tsql

我有一条类似下面的记录

item  | group  | score | updatedate |
------+--------+-------+------------+
item0 | group0 | 900   | 2018-01-01 |
item1 | group0 | 1000  | 2018-01-05 |
item1 | group1 | 1110  | 2018-01-01 |
item2 | group0 | 850   | 2018-01-01 |
item2 | group1 | 755   | 2018-01-02 |
item2 | group2 | 985   | 2018-01-03 |

如何仅在最新更新的情况下每个项目仅获得1条记录?记录应该这样

item  | group  | score | updatedate |
------+--------+-------+------------+
item0 | group0 | 900   | 2018-01-01 |
item1 | group0 | 1000  | 2018-01-05 |
item2 | group2 | 985   | 2018-01-03 |

它是SQL Server 2012,我已经尝试过使用该查询

SELECT a.item, a.updateddate, a.score
FROM pricelist a
LEFT OUTER JOIN pricelist b ON a.item = b.item AND a.UpdateDate < b.updateddate
WHERE b.item IS NULL
ORDER BY a.item desc;

但仍显示重复的项目

3 个答案:

答案 0 :(得分:4)

对此有几个答案。一种是使用TOP 1 WITH TIES

SELECT TOP 1 WITH TIES
       item,
       [group],
       score,
       updatedate
FROM YourTable
ORDER BY ROW_NUMBER() OVER (PARTITION BY item ORDER BY updatedate DESC);

否则,您可以使用CTE:

WITH CTE AS(
    SELECT item,
           [group],
           score,
           updatedate,
           ROW_NUMBER() OVER (PARTITION BY item ORDER BY updatedate DESC) AS RN
    FROM YourTable)
SELECT item,
       [group],
       score,
       updatedate
FROM CTE
WHERE RN = 1

答案 1 :(得分:2)

我们可以在此处尝试使用ROW_NUMBER

SELECT item, [group], score, updatedate
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY item ORDER BY updatedate DESC) rn
    FROM yourTable
) t
WHERE rn = 1
ORDER BY item;

注意:请勿使用保留的SQL关键字(例如GROUP)为列(或表等)命名。我必须对您的[group]列进行转义才能使查询工作。另外,如果您可能因为最近的updatedate而使一个项目有多条记录并列,并且希望包含所有关系,那么我们可以尝试将ROW_NUMBER替换为RANKDENSE_RANK

答案 2 :(得分:0)

以下查询将为您提供帮助。

SELECT 
    T.item
    ,T.[group]
    ,T.score
    ,T.updateddate
FROM 
#ItemTbl T 
inner join 
(
select 
    item
    ,MAX(updateddate) updateddate
FROM #ItemTbl
group by 
    item) T2 ON T.item=T2.item and t.updateddate=t2.updateddate