根据日期删除一对值中的一个

时间:2013-06-24 14:33:46

标签: sql sql-server algorithm select

说我有值:

Reference      Class  Timestamp
XXHAG70        11     2013-05-07 14:29:59.820
XXHAG70        11     2013-05-07 14:33:19.780
XXHAG70        17     2013-05-07 14:30:19.930
XXHAG70        17     2013-05-07 14:33:44.690
PAF7010        06     2008-11-06 10:25:07.140
PAF7010        06     2009-02-27 12:56:11.420

每个类都有重复的值,因此是配对的。我想为每个引用中的每个类选择最旧的时间戳。

4 个答案:

答案 0 :(得分:1)

您可以使用row_number函数。

SELECT  Reference ,
        Class ,
        Timestamp
FROM    ( SELECT    Reference ,
                    Class ,
                    Timestamp ,
                    ROW_NUMBER() OVER ( PARTITION BY Reference, Class ORDER BY Timestamp) AS rnum
          FROM      MyTable
        ) A
WHERE   rnum = 1;

答案 1 :(得分:0)

您可以使用MIN

SELECT MIN(TimeStamp)
FROM YourTable
WHERE Class IN (SELECT DISTINCT Class From YourTable)

答案 2 :(得分:0)

要获取每个班级/参考的最早版本,请使用MINGROUP BY

SELECT Reference, Class, MIN(Timestamp)
FROM myTable
GROUP BY Reference, Class

答案 3 :(得分:0)

这将删除除(reference, class)之外的所有最旧的行:

delete  from t1
from    (
        select  row_number() over (
                    partition by reference, class 
                    order by Timestamp desc) rn
        ,       *
        from    YourTable
        ) t1
where   t1.rn > 1

Live example at SQL Fiddle.