SQL/mysql - Select distinct/UNIQUE but return all columns?

前端 未结 18 1103
忘掉有多难
忘掉有多难 2020-11-22 12:08
SELECT DISTINCT field1, field2, field3, ......   FROM table

I am trying to accomplish the following sql statement but I want it to return all colum

18条回答
  •  旧巷少年郎
    2020-11-22 12:27

    Found this elsewhere here but this is a simple solution that works:

     WITH cte AS /* Declaring a new table named 'cte' to be a clone of your table */
     (SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY val1 DESC) AS rn
     FROM MyTable /* Selecting only unique values based on the "id" field */
     )
     SELECT * /* Here you can specify several columns to retrieve */
     FROM cte
     WHERE rn = 1
    

提交回复
热议问题