DISTINCT查询的SQL语法

时间:2014-07-26 22:39:30

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

我有一个带有DeptCode的员工表。我想要在Employee表中列出不同的DeptCode及其第一个创建日期。这还将告知哪个员工首次进入员工表中的特定部门。

我用过:

SELECT DISTINCT DEPTCODE, 
                CREATEDDATE 
FROM   EMPLOYEE 

日期返回不正确。

处理此问题的任何特定语法。

4 个答案:

答案 0 :(得分:3)

尝试:

SELECT DEPTCODE, 
       Min(CREATEDDATE) 
FROM   EMPLOYEE 
GROUP  BY DEPTCODE 

答案 1 :(得分:3)

如果您需要部门代码,最早的创建日期,员工的姓名,那么我会推荐窗口功能:

select deptcode, name, createddate
from (select e.*,
             row_number() over (partition by deptcode order by createddate) as seqnum
      from employee e
     ) e
where seqnum = 1;

答案 2 :(得分:1)

您可以使用GROUP BYMIN来实现此目标。

SELECT DEPTCODE, MIN(CREATEDDATE)
from EMPLOYEE
GROUP BY DEPTCODE

答案 3 :(得分:1)

像这样。

SELECT deptcode, 
       employee_name, 
       minddate 
FROM   employee 
       JOIN (SELECT deptcode, 
                    Min(createddate) mindate 
             FROM   employee 
             GROUP  BY deptcode) temp 
         ON employee.deptcode = temp.deptcode 
            AND createddate = mindate