簡體   English   中英

從單個SQL表中刪除除最新條目以外的所有條目

[英]Deleting all but the most recent entry from single SQL table

我有一個SQL表,其中每個客戶ID包含多個條目(某些客戶ID只有一個要保留的條目)。 我需要使用invoiceDate字段作為標記,刪除每個customerID以外的所有條目(最新條目除外)。

所以我需要從這里開始:

+------------+-------------+-----------+
| 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  |
+------------+-------------+-----------+

任何指導將不勝感激!

  1. 編寫查詢以選擇要刪除的所有行:
SELECT * FROM t
WHERE invoiceDate NOT IN (
    SELECT MAX(invoiceDate)
    -- "FROM t AS t2" isn't supported by MySQL, see http://stackoverflow.com/a/14302701/227576
    FROM (SELECT * FROM t) AS t2
    WHERE t2.customerId = t.customerId
    GROUP BY t2.customerId
)

在大型數據庫上,這可能需要很長時間。

  1. 如果您滿意,請將查詢更改為DELETE語句:
DELETE FROM t
WHERE invoiceDate NOT IN (
    SELECT MAX(invoiceDate)
    -- "FROM t AS t2" isn't supported by MySQL, see http://stackoverflow.com/a/14302701/227576
    FROM (SELECT * FROM t) AS t2
    WHERE t2.customerId = t.customerId
    GROUP BY t2.customerId
)

看到http://sqlfiddle.com/#!9/6e031/1

如果您有多行的日期是同一位客戶最近的日期,則必須尋找重復的行並決定要保留哪一行。 例如,在上面的SQL小提琴鏈接上查看customerId 2。

讓我們假設表名是transaction_table

create table test1 AS
select * from (
  select * from transaction_table order by customerID, invoiceDate desc) temp
group by customerID

您將在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
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))

這是在oracle中的處理方式。該查詢將刪除除最近添加的行以外的所有行。查看您的表結構,我假設invoicedate列為varchar2類型,因此將其轉換為使用date_date函數的日期

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM