简体   繁体   English

带有WHERE的DISTINCT子句

[英]DISTINCT clause with WHERE

How can I use the DISTINCT clause with WHERE? 如何在WHERE中使用DISTINCT子句? For example: 例如:

SELECT * FROM table WHERE DISTINCT email; -- email is a column name

I want to select all columns from a table with distinct email addresses. 我想从具有不同电子邮件地址的表中选择所有列。

If you mean all columns whose email is unique: 如果您指的是其电子邮件唯一的所有列:

SELECT * FROM table WHERE email in
     (SELECT email FROM table GROUP BY email HAVING COUNT(email)=1);

可能是:

SELECT DISTINCT email,id FROM table where id='2';
select t1.*
from YourTable as t1
  inner join
    (select email
     from YourTable
     group by email
     having count(email) = 1 ) as t2
    on t1.email = t2.email   

You can use the HAVING clause. 您可以使用HAVING子句。

SELECT * 
FROM tab_name
GROUP BY email_id
HAVING COUNT(*) = 1;

One simple query will do it: 一个简单的查询就可以了:

SELECT * 
FROM table 
GROUP BY email 
HAVING COUNT(*) = 1;

Wouldn't this work: 这不会起作用:

 SELECT email FROM table1 t1 
          where UNIQUE(SELECT * FROM table1 t2); 

简单查询此查询选择电子邮件唯一的表中的所有记录:

select distinct email,* from table_name

If you have a unique column in your table (eg tableid) then try this. 如果表中有一个唯一的列(例如tableid),那么试试这个。

SELECT EMAIL FROM TABLE WHERE TABLEID IN 
(SELECT MAX(TABLEID), EMAIL FROM TABLE GROUP BY EMAIL)

Try: 尝试:

SELECT * FROM table GROUP BY email

  • This returns all rows with a unique email taken by the first ID appearance (if that makes sense) 这将返回所有行,其中包含第一个ID外观所采用的唯一电子邮件(如果这有意义)
  • I assume this is what you were looking since I had about the same question but none of these answers worked for me. 我认为这是你所看到的,因为我有同样的问题,但这些答案都不适合我。

You can use ROW_NUMBER(). 您可以使用ROW_NUMBER()。 You can specify where conditions as well. 您也可以指定条件。 (eg Name LIKE'MyName% in the following query) (例如,在以下查询中Name LIKE'MyName%

SELECT  *
FROM    (SELECT ID, Name, Email,
            ROW_NUMBER() OVER (PARTITION BY Email ORDER BY ID) AS RowNumber
     FROM   MyTable
     WHERE  Name LIKE 'MyName%') AS a
WHERE   a.RowNumber = 1

SELECT DISTINCT dbo.Table.Email,dbo.Table.FirstName dbo.Table.LastName,dbo.Table.DateOfBirth(etc)FROM dbo.Table.Contacts WHERE Email ='name @ email';

查询:

Select *, (Select distinct email) from Table1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM