SQL - 根据两列选择最新的唯一

时间:2018-03-06 13:06:40

标签: sql db2 unique distinct

我在DB2 Warehouse表中有一个名为TEST的表:

    DATETIME                NAME  TYPE ANOMALY  CRE_DATE
0   2018-03-05 14:50:30     TEST    UV  0   2018-03-03 12:48:10.058288
1   2018-03-05 14:51:30     TEST    UV  0   2018-03-03 12:50:38.574614
2   2018-03-05 14:51:30     TEST    UV  0   2018-03-03 12:52:01.705416
3   2018-03-05 14:51:30     TEST    UV  0   2018-03-05 13:45:56.937965

我想要做的是选择最新的行(基于CRE_DATE),其中DATETIME的明确值为DATETIME is >= (CURRENT DATE -3 DAYS)NAME='TEST'。我尝试从这个查询开始,但我无法让它工作:

SELECT 
    DISTINCT DATETIME, 
    NAME, 
    TYPE, 
    ANOMALY, 
    CRE_DATE 
FROM 
    ML_ANOMALY_EVALUATION 
WHERE 
    ANOMALY=FALSE AND 
    NAME='TEST' 
ORDER BY 
    CRE_DATE DESC

1 个答案:

答案 0 :(得分:1)

在DB2中,最简单的方法是使用row_number()

SELECT mae.*
FROM (SELECT mae.*,
             ROW_NUMBER() OVER (PARTITION BY datetime ORDER BY CRE_DATE DESC) as seqnum
      FROM ML_ANOMALY_EVALUATION mae
      WHERE ANOMALY = FALSE AND NAME = 'HOG.683KQC206' 
     ) mae
WHERE seqnum = 1
ORDER BY CRE_DATE DESC;