如何选择不同的记录

时间:2014-05-06 09:47:55

标签: sql

我想从我的数据中选择不同的记录,此时它会显示重复的记录。以下是我的查询的外观:

SELECT DISTINCT ID,
  FirstName,
  SecondName,
  Department,
  Company,
  TotalEmployee,
  COUNT(
  CASE TotalAwards
    WHERE 1
    THEN 1
    ELSE NULL
  END),
  COUNT(
  CASE TotalRespect
    WHERE 1
    THEN 1
    ELSE NULL
  END)
FROM tablename
GROUP BY FirstName,
  SecondName,
  Department,
  Company,
  TotalEmployee 

我已经包含了不同的词,但我仍然得到重复的结果

3 个答案:

答案 0 :(得分:0)

DISTINCT关键字与该列一起使用,您想要获得不同的值,ID始终是不同的。作为DISTINCT FirstName比名字将是不同的。

答案 1 :(得分:0)

您要么寻找:

SELECT FirstName,
  SecondName,
  Department,
  Company,
  TotalEmployee,
  COUNT(
  CASE TotalAwards
    WHERE 1
    THEN 1
    ELSE NULL
  END),
  COUNT(
  CASE TotalRespect
    WHERE 1
    THEN 1
    ELSE NULL
  END)
FROM tablename
GROUP BY FirstName,
  SecondName,
  Department,
  Company,
  TotalEmployee 

OR

SELECT ID,
  FirstName,
  SecondName,
  Department,
  Company,
  TotalEmployee,
  COUNT(
  CASE TotalAwards
    WHERE 1
    THEN 1
    ELSE NULL
  END),
  COUNT(
  CASE TotalRespect
    WHERE 1
    THEN 1
    ELSE NULL
  END)
FROM tablename
GROUP BY ID, 
FirstName,
  SecondName,
  Department,
  Company,
  TotalEmployee 

答案 2 :(得分:0)

你可以使用row_number()和partition by()来获得所需的结果

尝试这样:

select * from
(
select *,rn=row_number()over(partition by Totalawards,totalrespect order by Firstname)
from table
)x
where x.rn=1