我有这样的表A:
ID | L1 |L2 | Date
-- |----- |---- | ---------
1 | A | B | 2003-01-01
---|------|-----|----------
2 | A | B | 2004-05-01
---|------|-----|----------
3 | B | C | 2003-01-01
---|------|-----|-----------
4 | B | C | 9999-12-31
---|------|-----|-----------
5 | C | D | 1998-02-03
---|------|-----|-----------
6 | C | D | 2004-05-01
正常情况是对于一对字母(AB,BC,CD)是一个日期=' 9999-12-31'。所以对于两对字母(AB,CD),我想念日期' 9999-12-31' 我需要写一个查询来查看这些字母和ID。
我写了一个查询(看一对字母的最大日期)
select distinct L1, L2, max(date) from A GROUP BY
L1, L2
having max(date)<>'9999-12-31'
此查询显示正确的行,但我还需要查看ID,这是我无法做到的。有谁知道如何编写查询以查看ID? ID始终是唯一的
谢谢!
答案 0 :(得分:1)
如果你想要没有任何日期等于9999-12-31的L1,L2对的所有行,Gordon提供了一个解决方案。
这是一个解决方案,以防您只查找没有任何日期等于9999-12-31的对L1,L2,对于这些对,您只需要具有最新日期的行。 / p>
with
table_A ( id, l1, l2, dt ) as (
select 1, 'A', 'B', date '2003-01-01' from dual union all
select 2, 'A', 'B', date '2004-05-01' from dual union all
select 3, 'B', 'C', date '2003-01-01' from dual union all
select 4, 'B', 'C', date '9999-12-31' from dual union all
select 5, 'C', 'D', date '1999-02-03' from dual union all
select 6, 'C', 'D', date '2004-05-01' from dual
)
select id, l1, l2, dt
from (
select id, l1, l2, dt,
row_number () over (partition by l1, l2 order by dt desc) rn
from table_A
)
where rn = 1
and dt != date '9999-12-31'
;
ID L1 L2 DT
------ -- -- -------------------
2 A B 2004-05-01 00:00:00
6 C D 2004-05-01 00:00:00
答案 1 :(得分:0)
尝试./sql_to_csv.sh my_query.sql out.csv
:
not exists
这假定&#34; date&#34;列存储为字符串,或者您具有日期格式设置,因此select a.*
from a a
where not exists (select 1
from a a2
where a2.l1 = a.l1 and a2.l2 = a.l2 and
a2.date = '9999-12-31'
);
被正确解释(如示例查询所示)。否则,您可以使用:
'9999-12-31'
编辑:
如果您希望a2.date = date '9999-12-31'
/ l2`组合的最高日期不是最大值,那很容易:
l1