我知道这个问题之前已经得到了回答,但也许是因为我在DB2或者其他什么东西,但我找不到适合我的解决方案。
我需要根据重复的KEY列的值选择每条记录中的一条(最近的)。
这是数据:
KEY TIME_STAMP STATUS
A 1992-06-30-00.00.00.100000 O
A 1992-02-03-00.00.00.100000 O
A 1991-12-20-00.00.00.100000 O
B 1992-11-19-00.00.00.100000 P
B 1992-11-17-00.00.00.100000 O
B 1992-10-08-00.00.00.100000 O
B 1992-09-24-00.00.00.100000 O
B 1992-09-18-00.00.00.100000 O
C 1984-06-21-00.00.00.100000 O
C 1984-06-05-00.00.00.100000 U
D 1986-04-22-00.00.00.100000 O
D 1986-04-14-00.00.00.100000 O
D 1986-03-16-00.00.00.100000 O
D 1986-03-07-00.00.00.100000 R
E 1985-04-03-00.00.00.100000 O
F 1987-08-14-00.00.00.100000 M
F 1987-07-17-00.00.00.100000 A
我需要它:
KEY TIME_STAMP STATUS
A 1992-06-30-00.00.00.100000 O
B 1992-11-19-00.00.00.100000 P
C 1984-06-21-00.00.00.100000 O
D 1986-04-22-00.00.00.100000 O
E 1985-04-03-00.00.00.100000 O
F 1987-08-14-00.00.00.100000 M
请注意,只保留最新的KEY类型。
所以这是我到目前为止的代码......它实际上是从一个巨大的表中创建顶级数据:
SELECT KEY, TIME_STAMP, STATUS
FROM HIST
WHERE STATUS IN ('P','O','U','R','M','A')
AND TIME_STAMP < '1993-01-01-00.00.00.100000'
ORDER BY KEY, TIME_STAMP DESC
我不知道该怎么做才能进一步削减它。
答案 0 :(得分:2)
您可以使用窗口函数:
select *
from (
select KEY,
TIME_STAMP,
STATUS,
row_number() over (partition by KEY order by TIME_STAMP desc) as rn
FROM HIST
WHERE STATUS IN ('P','O','U','R','M','A')
AND TIME_STAMP < '1993-01-01-00.00.00.100000'
)
WHERE rn = 1;
答案 1 :(得分:1)
其他方法,但Jorge方法更好
with perimeter as (
select KEY, TIME_STAMP, STATUS
FROM HIST
WHERE STATUS IN ('P','O','U','R','M','A') AND TIME_STAMP < '1993-01-01-00.00.00.100000'
)
select distinct f3.* from perimeter f1
inner join lateral
(
select * from perimeter f2
where f1.key=f2.key
order by f2.TIME_STAMP desc
fetch first rows only
) f3 on 1=1