Home [SQL] Delete 刪除重複列(Row)
Post
Cancel

[SQL] Delete 刪除重複列(Row)

語法

1
2
DELETE FROM table_name
WHERE condition
1
2
3
DELETE FROM table_name 
WHERE 主索引鍵 NOT IN
    (SELECT MAX(主索引鍵) From table_name GROUP BY 欄位1, 欄位2, 欄位3)
1
2
3
4
delete from Product 
where ID not in (
    select Max(ID) from Product group by 產品名稱
)

範例

由商品清單來刪除群組名稱重複的資料(只留id最小值的)
(這例子不是很好)

1
2
3
4
--由商品清單來刪除群組名稱重複的資料(只留id最小值的)
delete from #商品清單
where 商品ID not in (
select min(商品ID) from #商品清單 group by 群組名稱)

先將資料Group by 一個重複的欄位(群組名稱),然後篩出主索引鍵(商品ID)
然後用 where in 這些資料,就可以篩出來了。(刪除的話,就是顛倒條件)

Select Into 先快速備份資料:

1
select * into table_name_backup from table_name

執行結果:

1
2
3
4
5
6
select * from #商品清單

商品ID	商品名稱	群組名稱	進貨單價	販賣單價
1	桌上型電腦	電腦主機	130000	180000
3	17吋螢幕	周邊設備	52000	40000
9	HUB	網路設備	6500	8400
This post is licensed under CC BY 4.0 by the author.