根据单个不同列选择唯一行

时间:2011-11-25 20:36:12

标签: sql-server tsql

我想选择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?

4 个答案:

答案 0 :(得分:85)

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;

答案 1 :(得分:30)

我假设您的意思是您不在乎使用哪一行来获取titleidcommentname值(您有&# 34; rob"对于所有行,但我不知道这是否实际上是在你的数据模型中强制执行的。如果是这样,那么您可以使用窗口函数返回给定电子邮件地址的第一行:

select
    id,
    title,
    email,
    commentname

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

from YourTable
) source

where RowNbr = 1

答案 2 :(得分:2)

由于你不关心返回哪个id我为每个电子邮件坚持使用MAX id来简化SQL查询,试试看

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

答案 3 :(得分:2)

如果您使用 MySql 5.7或更高版本,根据这些链接(MySql OfficialSO QA),我们可以选择每group by条记录一条记录需要任何集合函数。

因此可以将查询简化为此。

select * from comments_table group by commentname;

尝试执行here

中的查询