SQL,如何删除重复行并找到min(timeIn)和max(timeOut)

时间:2015-04-06 07:15:56

标签: sql-server

我只是想问一下如何使用不同的timeIntimeOut管理重复行。我的意思是,结果应该是没有重复的行具有相同的id,但同时该特定人的timeIn应该是最小timeIntimeOut应该是最后timeOutattDate必须在同一天。如何进行查询,任何想法?

这里有一些简单的代码:

SELECT 
    id, name, attend_date, Time_in, Time_out,
    count(1) as Count_person
FROM 
    employee
WHERE 
    attDate = '12/01/2015' AND Time_out IS NOT NULL 
GROUP BY 
    id, name, attend_date, Time_in, Time_out
HAVING 
    COUNT(1) > 1 

//音符。我只是一个初学者,并试图提高自己。

1 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER获取最新的time_in和最后time_out

WITH Cte AS(
    SELECT *,
        RN_Time_in = ROW_NUMBER() OVER(PARTITION BY id, attDate ORDER BY Time_in),
        RN_Time_Out = ROW_NUMBER() OVER(PARTITION BY id, attDate ORDER BY Time_Out DESC)
    FROM employee
)
SELECT *
FROM Cte
WHERE
    RN_Time_in = 1 
    AND RN_Time_Out = 1