我正试图获得记录保持在STATE'I'(无效)的最远日期,而不更新为'V'有效。这里有一个例子(DATE是desc的顺序):
--------------------------------
ID STATE DATE
--------------------------------
1 I 30/01/2017
1 I 25/01/2017 <-
1 V 20/01/2017
1 I 15/01/2017
2 I 25/01/2017
2 I 20/01/2017 <-
3 I 30/01/2017 <-
3 V 15/01/2017
3 I 10/01/2017
3 I 05/01/2017
预期结果:
--------------------------------
ID STATE DATE
--------------------------------
1 I 25/01/2017
2 I 20/01/2017
3 I 30/01/2017
答案 0 :(得分:2)
试试这个:
SELECT ID,STATE ,MIN(DATE) FROM FURTHEST t1
WHERE STATE = 'I'
AND NOT EXISTS(SELECT *
FROM FURTHEST t2
WHERE state = 'V' AND
t1.id = t2.id AND
t1.DATE < t2.DATE)
GROUP BY ID,STATE
ORDER BY ID;
答案 1 :(得分:1)
您可以使用not exists
运算符搜索未跟I
条记录的V
条记录,然后group by
id
最大日期:
SELECT id, MAX("date")
FROM mytable a
WHERE state = 'I' AND
NOT EXISTS (SELECT *
FROM mytable b
WHERE state = 'V' AND
a.id = b.id AND
a."date" < b."date")
GROUP BY id
注意:强>
date
是Oracle SQL中的保留字,因此必须对其进行转义 - 因此使用"date"
。
答案 2 :(得分:1)
你走了; 01.01.1900是一个想象的&#34;最短日期,用于简化某些ID没有&#34; V&#34;(alid)状态的情况。
SQL> WITH test (id, state, datum)
2 AS (SELECT 1, 'I', TO_DATE ('30.01.2017', 'dd.mm.yyyy') FROM DUAL
3 UNION
4 SELECT 1, 'I', TO_DATE ('25.01.2017', 'dd.mm.yyyy') FROM DUAL
5 UNION
6 SELECT 1, 'V', TO_DATE ('20.01.2017', 'dd.mm.yyyy') FROM DUAL
7 UNION
8 SELECT 1, 'I', TO_DATE ('15.01.2017', 'dd.mm.yyyy') FROM DUAL
9 UNION
10 --
11 SELECT 2, 'I', TO_DATE ('25.01.2017', 'dd.mm.yyyy') FROM DUAL
12 UNION
13 SELECT 2, 'I', TO_DATE ('20.01.2017', 'dd.mm.yyyy') FROM DUAL
14 )
15 SELECT id, state, datum
16 FROM test t
17 WHERE t.datum =
18 (SELECT MIN (t1.datum)
19 FROM test t1
20 WHERE t1.id = t.id
21 AND t1.state = 'I'
22 AND t1.datum >
23 (SELECT NVL (MAX (t2.datum), DATE '1900-01-01')
24 FROM test t2
25 WHERE t2.id = t.id AND t2.state = 'V'));
ID S DATUM
---------- - ----------
1 I 25.01.2017
2 I 20.01.2017
SQL>