SQL等效的Oracle" WHERE()IN"?

时间:2018-06-18 16:48:16

标签: sql sql-server oracle aggregation

在Oracle中,如果我想为所有ID选择最新条目的所有列(基于时间戳列),我可以这样做:

SELECT * FROM TABLE1 WHERE (TIMESTAMP,ID) IN
   (SELECT MAX(TIMESTAMP),ID FROM TABLE1 GROUP BY ID)

但是这个语句在SQL SMS(版本17.4)中不起作用。

我可以使用相同的声明吗?

3 个答案:

答案 0 :(得分:2)

您需要关联方法:

SELECT t.* 
FROM TABLE1 t
WHERE TIMESTAMP = (SELECT MAX(t1.TIMESTAMP) FROM TABLE1 t1 WHERE t1.ID = t.ID);

答案 1 :(得分:1)

通过内部联接可以轻松恢复状态

SELECT * FROM TABLE1 
INNER JOIN (
  SELECT MAX(TIMESTAMP) max_time,ID FROM TABLE1 GROUP BY ID
) t on t.max_time = TABLE1.TIMESTAMP and t.ID = TABLE1.ID

答案 2 :(得分:0)

您还可以使用分析查询:

SQL Fiddle

MS SQL Server 2017架构设置

CREATE TABLE Table1 ( ID int, ts DATETIME, rn INT );

INSERT INTO Table1 ( id, ts, rn )
SELECT 1, {ts '2018-01-01 00:00:00'}, 5 UNION ALL
SELECT 1, {ts '2018-01-01 01:00:00'}, 4 UNION ALL
SELECT 1, {ts '2018-01-01 02:00:00'}, 3 UNION ALL
SELECT 1, {ts '2018-01-01 03:00:00'}, 2 UNION ALL
SELECT 1, {ts '2018-01-01 04:00:00'}, 1 UNION ALL
SELECT 2, {ts '2018-01-01 00:00:00'}, 1 UNION ALL
SELECT 2, {ts '2018-01-01 01:00:00'}, 2 UNION ALL
SELECT 2, {ts '2018-01-01 02:00:00'}, 3 UNION ALL
SELECT 2, {ts '2018-01-01 03:00:00'}, 4 UNION ALL
SELECT 2, {ts '2018-01-01 04:00:00'}, 5;

查询1

SELECT *
FROM   (
  SELECT t.*,
         RANK() OVER ( PARTITION BY id ORDER BY ts DESC ) AS rnk
  FROM   TABLE1 t
) t
WHERE  rnk = 1

<强> Results

| ID |                   ts | rn | rnk |
|----|----------------------|----|-----|
|  1 | 2018-01-01T04:00:00Z |  1 |   1 |
|  2 | 2018-01-01T04:00:00Z |  5 |   1 |