从表中获取唯一数据

时间:2013-12-31 10:18:56

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

我有一个包含一些数据的表,如下所示。

enter image description here

我想从表中获取唯一数据,我尝试了下面的代码

SELECT
    sa.EMPID,
    sa.EMPNAME,
    sa.DEPTID
FROM dbo.Sample AS sa
LEFT OUTER JOIN dbo.Sample AS se ON sa.EMPID = se.EMPID

但无法获得结果。

我希望查询得到以下数据

enter image description here

有谁可以帮我解决这个问题..?

5 个答案:

答案 0 :(得分:5)

试试这个:

SELECT EMPNAME,
       DEPTID,
       MIN(EMPID) AS EMPID
       FROM  dbo.Sample
 GROUP BY EMPNAME, DEPTID

答案 1 :(得分:4)

试试这个 -

SELECT EMPID, EMPNAME, DEPTID
FROM (
    SELECT
        EMPID,
        EMPNAME,
        DEPTID,
        RowNum = ROW_NUMBER() OVER (PARTITION BY EMPNAME, DEPTID ORDER BY 1/0)
    FROM dbo.[Sample]
) t
WHERE RowNum = 1

答案 2 :(得分:3)

您可group by empnamedeptid,并选择最小empid

SELECT     MIN(sa.EMPID), sa.EMPNAME, sa.DEPTID
FROM       dbo.Sample AS sa LEFT OUTER JOIN
           dbo.Sample AS se ON sa.EMPID = se.EMPID
GROUP BY   sa.EMPNAME, sa.DEPTID

答案 3 :(得分:0)

试试这个

With tmp AS
FROM (SELECT S.EMPID,S.EMPNAME,S.DEPTID,RowNum = ROW_NUMBER() OVER (PARTITION BY S.EMPNAME, S.DEPTID ORDER BY S.EMPID)
    FROM dbo.[Sample] S LEFT JOIN dbo.[Sample] T ON T.EMPID = S.EMPID)     
SELECT EMPID,EMPNAME,DEPTID FROM tmp WHERE RowNum = 1

答案 4 :(得分:0)

这就是你想要的:

SELECT Min(EMPID) AS EMPID,
EMPNAME,
DEPTID
FROM dbo.Sample
Group By EMPNAME, DEPTID