1. 程式人生 > 其它 >sql根據多個欄位去重查詢 返回所有欄位

sql根據多個欄位去重查詢 返回所有欄位

技術標籤:SQLsql去重資料庫去重

book表中的資料:
在這裡插入圖片描述
根據所有欄位去重:

SELECT DISTINCT * from dbo.book 

sql根據多個欄位去重:

SELECT title,isbn,author_id ,page_count  from dbo.book 
group by title,isbn,author_id ,page_count
 

或者:
SELECT DISTINCT title,isbn,author_id ,page_count from dbo.book
在這裡插入圖片描述
sql根據多個欄位去重,並且返回所有欄位:


SELECT * from dbo.book a where id in (SELECT max(id) from dbo.book 
group by title,isbn,author_id ,page_count )

如果資料量比較大的話in會有效率問題,可以採用以下寫法

SELECT a.* from dbo.book a , (SELECT max(id) as id from dbo.book 
group by title,isbn,author_id ,page_count )b where a.id = b.id

在這裡插入圖片描述
有問題歡迎指正