如何获取每个时间戳的最新行

时间:2017-08-22 15:22:35

标签: sql select db2

我有:

SELECT * FROM TABLE1 WHERE TIMESTAMP IN (SELECT TIMESTAMP FROM TABLE2 WHERE STATUS='1' AND TIMESTAMP_PROCESSED BETWEEN '2017-01-07-00.00.00.000000' and '2017-01-17-00.00.00.000000')

我得到8行,其中4行为TIMESTAMP' 2017-01-09 11:26:29.434254'和其他四个2017-01-11 15:09:51.935322'使用不同的TIMESTAMP_OFFER(TABLE1列)。我怎样才能为每个TIMESTAMP获得最新的TIMESTAMP_OFFER?换句话说,我只需要两行而不是八行。

感谢。

更新:

我现在有这个查询:

SELECT TIMESTAMP, STATUS, MAX(TIMESTAMP_OFFER) FROM TABLE1 WHERE TIMESTAMP IN (SELECT TIMESTAMP FROM TABLE2 WHERE STATUS='1' AND TIMESTAMP_PROCESSED BETWEEN '2017-01-07-00.00.00.000000' and '2017-01-17-00.00.00.000000') GROUP BY TIMESTAMP, STATUS

但是现在我得到了四行结果(每个时间戳有两行),因为我在每个TIMESTAMP / TIMESTAMP OFFER中有两个STATUS值:

-----------------------------------------------------------------------
| TIMESTAMP                  | STATUS | TIMESTAMP_OFFER               |
-----------------------------------------------------------------------
|2017-01-09 11:26:29.434254  | E      | 2017-02-01 16:05:02.221179    |
-----------------------------------------------------------------------
|2017-01-09 11:26:29.434254  | P      | 2017-02-01 16:05:02.221179    |
-----------------------------------------------------------------------
|2017-01-11 15:09:51.935322  | E      | 2017-02-11 12:00:50.410959    |
-----------------------------------------------------------------------
|2017-01-11 15:09:51.935322  | P      | 2017-02-11 12:00:50.410959    |
-----------------------------------------------------------------------

在这种情况下,我只需要这个:

-----------------------------------------------------------------------
| TIMESTAMP                  | STATUS | TIMESTAMP_OFFER               |
-----------------------------------------------------------------------
|2017-01-09 11:26:29.434254  | E      | 2017-02-01 16:05:02.221179    |
-----------------------------------------------------------------------
|2017-01-11 15:09:51.935322  | E      | 2017-02-11 12:00:50.410959    |
-----------------------------------------------------------------------

我如何得到它?

2 个答案:

答案 0 :(得分:0)

使用TIMESTAMP_PROCESSED上的MAX()函数并执行GROUP BY

答案 1 :(得分:0)

SELECT * FROM TABLE1 WHERE TIMESTAMP IN (
SELECT TIMESTAMP FROM TABLE2 WHERE TIMESTAMP_PROCESSED IN
    (SELECT max(TIMESTAMP_PROCESSED) FROM TABLE2 WHERE STATUS='1' AND TIMESTAMP_PROCESSED BETWEEN '2017-01-07-00.00.00.000000' and '2017-01-17-00.00.00.000000'))