我的数据类似于
+-------+------------+------------+
| ID | START_DATE | END_DATE |
+-------+------------+------------+
| 12345 | 11/09/2008 | 02/02/2011 |
| 12345 | 11/09/2008 | 11/09/2008 |
| 12345 | 02/02/2011 | 12/31/9999 |
+-------+------------+------------+
我希望如何 -
+-------+------------+------------+
| ID | START_DATE | END_DATE |
+-------+------------+------------+
| 12345 | 11/09/2008 | 02/02/2011 |
| 12345 | 02/02/2011 | 12/31/9999 |
+-------+------------+------------+
基本上我删除 ID 列和 START_DATE 下的重复项,并保留最新的 END_DATE 一
我的查询 - 使用此项我可以看到重复项
SELECT * FROM (SELECT ID,START_DATE,END_DATE,
ROW_NUMBER() OVER (PARTITION BY ID, START_DATE order by END_DATE desc) RN
FROM MYTABLE) a WHERE a.RN>1
上面的 SELECT 查询工作得很好但是当我尝试删除时使用相同的查询 -
DELETE FROM (SELECT ID,START_DATE,END_DATE,
ROW_NUMBER() OVER (PARTITION BY ID, START_DATE order by END_DATE desc) RN
FROM MYTABLE) a WHERE a.RN>1
我收到提示 -
错误[42000] [Teradata] [ODBC Teradata驱动程序] [Teradata数据库] 语法错误:不允许派生表进行删除。
我问 -
有没有办法可以删除这些欺骗而无需进入派生表或任何其他方式来转换当前查询而不使用派生表
答案 0 :(得分:3)
如果(id, start_date, end_date)
上没有重复项,则可以执行以下操作:
delete from mytable t
where t.end_date < (select max(t2.end_date)
from mytable t2
where t2.id = tid and t2.start_date = t.start_date
);
答案 1 :(得分:0)
您可以删除第一个查询选择并使用其ID的记录:
Delete from MYTABLE WHERE ID IN (
SELECT ID FROM (SELECT ID,START_DATE,END_DATE,
ROW_NUMBER() OVER (PARTITION BY ID, START_DATE order by END_DATE desc) RN
FROM MYTABLE) a WHERE a.RN>1)