Nice programing

단일 고유 열을 기반으로 고유 행 선택

nicepro 2020. 11. 14. 11:04
반응형

단일 고유 열을 기반으로 고유 행 선택


가있는 행을 선택하고 싶습니다 distinct email. 아래 예제 표를 참조하십시오.

+----+---------+-------------------+-------------+
| id | title   | email             | commentname |
+----+---------+-------------------+-------------+
|  3 | test    | rob@hotmail.com   | rob         |
|  4 | i agree | rob@hotmail.com   | rob         |
|  5 | its ok  | rob@hotmail.com   | rob         |
|  6 | hey     | rob@hotmail.com   | rob         |
|  7 | nice!   | simon@hotmail.com | simon       |
|  8 | yeah    | john@hotmail.com  | john        |
+----+---------+-------------------+-------------+

원하는 결과는 다음과 같습니다.

+----+-------+-------------------+-------------+
| id | title | email             | commentname |
+----+-------+-------------------+-------------+
|  3 | test  | rob@hotmail.com   | rob         |
|  7 | nice! | simon@hotmail.com | simon       |
|  8 | yeah  | john@hotmail.com  | john        |
+----+-------+-------------------+-------------+

어떤 id열 값이 반환 되는지 상관하지 않습니다 . 필요한 SQL은 무엇입니까?


TSQL에서 빠른 것

SELECT a.*
FROM emails a
INNER JOIN 
  (SELECT email,
    MIN(id) as id
  FROM emails 
  GROUP BY email 
) AS b
  ON a.email = b.email 
  AND a.id = b.id;

나는 당신이를 얻기 위해 사용되는 행 상관하지 않는 것을 의미 있으리라 믿고있어 title, id그리고 commentname당신이 모든 행에 대해 "강탈"가 (값,하지만 그 시행 될 무언가가 실제로 나도 몰라 데이터 모델에서). 그렇다면 윈도우 함수를 사용하여 주어진 이메일 주소에 대한 첫 번째 행을 반환 할 수 있습니다.

select
    id,
    title,
    email,
    commentname

from
(
select 
    *, 
    row_number() over (partition by email order by id) as RowNbr 

from YourTable
) source

where RowNbr = 1

어떤 ID를 반환할지 신경 쓰지 않으므로 SQL 쿼리를 단순화하기 위해 각 이메일에 대해 MAX ID를 고수하므로 시도해보십시오.

;WITH ue(id)
 AS
 (
   SELECT MAX(id)
   FROM table
   GROUP BY email
 )
 SELECT * FROM table t
 INNER JOIN ue ON ue.id = t.id

If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by with out the need of any aggregate functions.

So the query can be simplified to this.

select * from comments_table group by commentname;

Try out the query in action here

참고URL : https://stackoverflow.com/questions/8273987/select-unique-rows-based-on-single-distinct-column

반응형