按日期时间分组结果

时间:2015-07-06 07:06:02

标签: sql sql-server sql-server-2012

我尝试获得员工的第一个(最低)开始日期:

SELECT a.StartDate, a.EmpID, b.fullname FROM Employees a 
LEFT JOIN dbo.info b ON a.EmpID = b.EmpID
WHERE 
    type = 800 
    GROUP By EmpId
    ORDER BY fullname

结果类似于:

StartDate | EmpId
1992-12-01 00:00:00.000 | 7
2014-01-01 00:00:00.000 | 7
2015-01-01 00:00:00.000 | 7
1992-12-01 00:00:00.000 | 10
2014-01-01 00:00:00.000 | 10
2015-01-01 00:00:00.000 | 10
1992-01-01 00:00:00.000 | 16
2014-01-01 00:00:00.000 | 16
2015-01-01 00:00:00.000 | 16

为了获得每个员工的最低日期,我尝试了这个,但却导致了错误。

SELECT MIN(a.StartDate), a.EmpID, b.fullname FROM Employees a 
LEFT JOIN dbo.info b ON a.EmpID = b.EmpID
WHERE 
    type = 800 
    GROUP By EmpId
    ORDER BY fullname

获得结果的正确查询是什么:

StartDate | EmpId
1992-12-01 00:00:00.000 | 7
1992-12-01 00:00:00.000 | 10
1992-01-01 00:00:00.000 | 16

5 个答案:

答案 0 :(得分:2)

SELECT a.StartDate, a.EmpID, b.fullname 
FROM Employees a 
LEFT JOIN dbo.info b ON a.EmpID = b.EmpID
WHERE type = 800 
AND NOT EXISTS ( SELECT 'a'
                 FROM Employees a2
                 WHERE a.EmpID = a2.EmpID
                 AND a2.StartDate < a.StartDate
               )

答案 1 :(得分:1)

您想要每EmpID个结果行,这就是您应该分组的列:

SELECT   MIN(StartDate), EmpID 
FROM     Employees
WHERE    type = 800 AND EmpID BETWEEN 1 AND 500
GROUP BY EmpID

答案 2 :(得分:0)

num2 = num1 - (1/(3*3))

你的小组是在错误的领域。

SELECT MIN(StartDate), EmpID FROM Absences
WHERE type = 800 
AND EmpID BETWEEN 1 AND 500
GROUP BY StartDate

答案 3 :(得分:0)

使用此查询, 这将停止重复数据

  SELECT Distinct StartDate, EmpID FROM Employees

答案 4 :(得分:0)

SELECT DISTINCT a.EmpID, b.fullname, a.StartDate FROM Employees a 
LEFT JOIN dbo.info b 
ON a.EmpID = b.EmpID
WHERE type = 800    
ORDER BY a.StartDate, b.fullname ASC