我有一张这样的表
ID | Type | Val0 | Creation_date
1 | A | V1 | 24sep, 2011
2 | B | X1 | 15 dec, 2001
3 | A | V1 | 27oct, 2008
4 | A | V2 | 19oct, 2003
5 | B | X2 | 15 dec, 2000
6 | C | X3 | 23Dec, 2001
7 | B | X2 | 15 dec, 1990
我想只保留特定类型的最新值,并提取旧的值。因此,对于上表,我希望将这些项目提取出来 - V2,X2,我可以在以后删除。
由于A的最新值为V1,因此B的最新值为X1,而C的最新值为X3。
有人可以建议我如何使用SQL来做到这一点吗?
答案 0 :(得分:0)
如果您只想要这些值,可以使用keep
:
select type,
max(val0) keep (dense_rank first order by creation_date asc) as latest_val0
from t
group by type;
如果您想要整行,请使用row_number()
:
select t.*
from (select t.*,
row_number() over (partition by type order by creation_date asc) as seqnum
from t
) t
where seqnum = 1;
答案 1 :(得分:0)
Oracle安装程序:
CREATE TABLE table_name ( ID, Type, Val, Creation_date ) AS
SELECT 1, 'A', 'V1', DATE '2011-09-24' FROM DUAL UNION ALL
SELECT 2, 'B', 'X1', DATE '2001-12-15' FROM DUAL UNION ALL
SELECT 3, 'A', 'V1', DATE '2008-10-27' FROM DUAL UNION ALL
SELECT 4, 'A', 'V2', DATE '2003-10-19' FROM DUAL UNION ALL
SELECT 5, 'B', 'X2', DATE '2000-12-15' FROM DUAL UNION ALL
SELECT 6, 'C', 'X3', DATE '2001-12-23' FROM DUAL UNION ALL
SELECT 7, 'B', 'X2', DATE '1990-12-15' FROM DUAL;
<强>查询强>:
SELECT ID,
TYPE,
val,
Creation_date
FROM (
SELECT t.*,
LAST_VALUE( val ) OVER (
PARTITION BY type
ORDER BY creation_date
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
) AS last_val
FROM table_name t
)
WHERE val <> last_val;
<强>输出强>:
ID TYPE VAL CREATION_DATE
---------- ---- --- -------------------
4 A V2 2003-10-19 00:00:00
7 B X2 1990-12-15 00:00:00
5 B X2 2000-12-15 00:00:00