如何从此表中检索DISTINCT值?

时间:2012-10-12 21:55:33

标签: sql sql-server sql-server-2008 tsql

这是我的表值。 (7条记录)

SELECT * FROM tbl1

由于我的代表很低,我无法发布图片。所以我在这里链接它 http://i.stack.imgur.com/CFl0u.png

我写了一个查询以避免最后一条记录,但我仍然得到了最后一条记录。 (我需要的只是不同的电子邮件)

SELECT DISTINCT CandEmail,CandName,EmployerId,ContNum,IsDeleted,CandPortalId FROM tbl1
WHERE EmployerId = 7 AND IsDeleted = 0

上述查询仍会检索具有上一个重复电子邮件记录的相同7条记录。

4 个答案:

答案 0 :(得分:5)

您可以将ROW_NUMBEROVER子句一起使用:

WITH CTE AS
(
  SELECT CandEmail,CandName,EmployerId,ContNum,IsDeleted,CandPortalId
        , RN = ROW_NUMBER() OVER (PARTITION BY CandEmail ORDER BY ContNum DESC)
  FROM tbl1
  WHERE IsDeleted = 0
)
SELECT CandEmail,CandName,EmployerId,ContNum,IsDeleted,CandPortalId
FROM CTE WHERE RN = 1

OVER Clause (Transact-SQL)

  

确定行之前的行集的分区和排序   应用关联的窗口函数。也就是OVER子句   在查询结果中定义窗口或用户指定的行集   组。然后,窗口函数计算每行中的一个值   窗口。

答案 1 :(得分:2)

使用group by: -

  SELECT CandEmail, MAX(CandName), MAX(EmployerId), MAX(ContNum), MAX(IsDeleted),          MAX(CandPortalId)
  FROM tbl1
  WHERE EmployerId = 7 AND IsDeleted = 0
  GROUP BY CandEmail

答案 2 :(得分:1)

SELECT CandEmail, 
       MAX(CandName), 
       7 [EmployerId], 
       MAX(ContNum), 
       0 [IsDeleted], 
       MAX(CandPortalId)
FROM   tbl1
WHERE  EmployerId = 7 AND IsDeleted = 0
GROUP BY CandEmail

答案 3 :(得分:1)

如果你不关心你得到哪个ContNum,那么你可以在该字段周围放置一个聚合函数,然后GROUP BY其余部分:

SELECT CandEmail,
  CandName,
  EmployerId,
  MIN(ContNum) ContNum,  -- or you can use MAX()
  IsDeleted,
  CandPortalId 
FROM tbl1
WHERE EmployerId = 7 
  AND IsDeleted = 0
GROUP BY CandEmail,
  CandName,
  EmployerId, 
  IsDeleted,
  CandPortalId 

或者正如其他人指出的那样,你应该在其他字段上使用聚合函数,除非你确定这些列中没有不同的值:

SELECT CandEmail,
  min(CandName) CandName,
  min(EmployerId) EmployerId,
  MIN(ContNum) ContNum,  -- or you can use MAX()
  min(IsDeleted) IsDeleted,
  min(CandPortalId) CandPortalId
FROM tbl1
WHERE EmployerId = 7 
  AND IsDeleted = 0
GROUP BY CandEmail