Mysql 从单个SQL表中删除除最新条目以外的所有条目
我有一个SQL表,其中包含每个customerID的多个条目。有些customerID只有一个条目需要保留。我需要使用invoiceDate字段作为标记,删除每个customerID中除最新条目以外的所有条目 所以我需要从这里开始:Mysql 从单个SQL表中删除除最新条目以外的所有条目,mysql,sql,Mysql,Sql,我有一个SQL表,其中包含每个customerID的多个条目。有些customerID只有一个条目需要保留。我需要使用invoiceDate字段作为标记,删除每个customerID中除最新条目以外的所有条目 所以我需要从这里开始: +------------+-------------+-----------+ | customerID | invoiceDate | invoiceID | +------------+-------------+-----------+ |
+------------+-------------+-----------+
| customerID | invoiceDate | invoiceID |
+------------+-------------+-----------+
| 1 | 1393995600 | xx |
| 1 | 1373688000 | xx |
| 1 | 1365220800 | xx |
| 2 | 1265220800 | xx |
| 2 | 1173688000 | xx |
| 3 | 1325330800 | xx |
+------------+-------------+-----------+
为此:
+------------+-------------+-----------+
| customerID | invoiceDate | invoiceID |
+------------+-------------+-----------+
| 1 | 1393995600 | xx |
| 2 | 1265220800 | xx |
| 3 | 1325330800 | xx |
+------------+-------------+-----------+
任何指导都将不胜感激
编写查询以选择要删除的所有行:
从t中选择*
发票日期不在哪
选择MAXinvoiceDate
-由于MySQL不支持t2,请参阅http://stackoverflow.com/a/14302701/227576
从选择*从t到t2
其中t2.customerId=t.customerId
按t2.customerId分组
在大型数据库上,这可能需要很长时间
如果您满意,请将查询更改为DELETE语句:
从t中删除
发票日期不在哪
选择MAXinvoiceDate
-由于MySQL不支持t2,请参阅http://stackoverflow.com/a/14302701/227576
从选择*从t到t2
其中t2.customerId=t.customerId
按t2.customerId分组
看
如果有多行的日期是同一客户的最新日期,则必须查找重复的行,并自行决定要保留哪一行。例如,查看上面SQL fiddle链接上的customerId 2。让我们假设表名为transaction\u table 您将在test1表中获得输出数据。试试这个
with todelete as
(
select
CustomerId, InvoiceId, InvoiceDate, Row_Number() over (partition by CustomerId order by InvoiceDate desc) as Count
from DeleteDuplicate
)
delete from todelete
where count > 1
这就是在oracle中的操作方式。此查询将删除除最近添加的行以外的所有行。查看您的表结构,我假设invoicedate列为varchar2类型,因此将其转换为用于此处的日期函数的日期我建议您研究SQL关键字MAX和GROUP by,我对他们很熟悉,但我似乎无法提出一个问题来完成我需要的任务。我尝试了几个嵌套查询,结果不一。我最近的尝试删除了大约30000行中除1行以外的所有行。这是的一个缺陷,所以这个答案经常回答得很差,实际上很难区分小麦和谷壳。也就是说,也有很多好的答案。不幸的是,他们没有一个在那里VvtHanks pyb,你的答案对我来说很有用,只是有一个小修正。我有一个1093错误-您不能指定目标表。。。对于FROM子句中的更新。解决方案是将代码第5行中的“FROM t as t2”替换为“FROM SELECT*FROM t as t2”。更多信息-@rocky我不知道!谢谢你的评论,我正在更新我的答案。谢谢seahawk,上面pyb的解决方案似乎效果最好。
with todelete as
(
select
CustomerId, InvoiceId, InvoiceDate, Row_Number() over (partition by CustomerId order by InvoiceDate desc) as Count
from DeleteDuplicate
)
delete from todelete
where count > 1
delete from ex_4 where
rowid in
(select rowid
from ex_4 a
where to_date(invoicedate,'DDMMYYYY') = (select max(to_date(invoicedate,'DDMMYYYY')) from ex_4 b where a.customerid != b.customerid))