2017-08-27 106 views
0

我需要幫助才能在一天內只選擇最後一個更新的行進入/退出。Query to select one row for one date in SQL Server

我使用這個查詢:

SELECT  
    convert(nvarchar(20), EmpID) as EmpID, ID, 
    DATENAME(dw, date1) AS day, date1 AS date, 
    PunchDateTime AS timein, 
    COALESCE((SELECT MAX(PunchDateTime) AS Expr1 
       FROM PunchData AS b 
       WHERE empid = '61039' 
       AND (EmpID = a.EmpID) 
       AND (PunchType = 4) 
       AND PunchDateTime between a.PunchDateTime and dateadd(hour, 17, a.PunchDateTime)), 
      (SELECT MIN(PunchDateTime) AS Expr1 
       FROM PunchData AS b 
       WHERE empid = '61039' 
       AND (EmpID = a.EmpID) 
       AND (ID >= a.ID) 
       AND (PunchType = 1) 
       AND date1 = a.date1), 0) AS timeout 
FROM   
    dbo.PunchData AS a 
WHERE  
    empid = '61039' 
    AND (PunchType = 1) 
GROUP BY 
    EmpID, ID, DATENAME(dw, date1), date1, PunchDateTime 

UNION ALL 

SELECT  
    convert(nvarchar(20), EmpID) as EmpID, ID, 
    DATENAME(dw, dateadd(hour, -12, PunchDateTime)) AS day, 
    convert(date, COALESCE((SELECT Min(PunchDateTime) AS Expr1 
          FROM PunchData AS b 
          WHERE EmpID = '61039' 
           AND (EmpID = a.EmpID) 
           AND (PunchType = 1) 
           AND PunchDateTime between dateadd(hour, -17, a.PunchDateTime) 
                and a.PunchDateTime), 
          dateadd(hour, -12, PunchDateTime))) AS date, 
    COALESCE((SELECT Min(PunchDateTime) AS Expr1 
       FROM PunchData AS b 
       WHERE EmpID = '61039' 
       AND (EmpID = a.EmpID) 
       AND (PunchType = 1) 
       AND PunchDateTime between dateadd(hour, -17, a.PunchDateTime) 
             and a.PunchDateTime), 
      (SELECT Max(PunchDateTime) AS Expr1 
       FROM PunchData AS b 
       WHERE EmpID = '61039' 
       AND (EmpID = a.EmpID) 
       AND (ID = a.ID) 
       AND (PunchType = 4) 
       AND date1 = a.date1), 0) AS timein, 
    PunchDateTime as timeout 
FROM   
    dbo.PunchData AS a 
WHERE  
    (PunchType = 4) 
    AND empid = '61039' 
GROUP BY 
    EmpID, ID, DATENAME(dw, date1), date1, PunchDateTime 

SQL output image

+2

你應該作出努力,是** **一致的與您如何編寫SQL關鍵字 - * *要麼把它們寫在所有大寫('SELECT','FROM ','CONVERT'),或者將它們寫成全部小寫字母(select,from,convert)或混合大小寫形式(Select,From,Convert) - 但請**選取一種樣式**然後**粘貼它* * - 不要將它們全部混合在一起! –

回答

0

你可以換一個CTE整個查詢,然後做後續選擇從CTE吧?

這樣的事情也許是:

;with mycte as (
select 1 as ID , '2017-08-01' as date1 
union all 
select 1 as ID , '2017-08-02' as date1 
) 

Select distinct mycte.* 
from mycte 
inner join mycte mycte2 
    on mycte.ID = mycte2.ID 
     and mycte.date1 = (select max(mycte3.date1) from mycte mycte3 where mycte3.id = mycte.ID) 
+0

我做到了,但之後,我怎麼只能選擇最後更新的行 –

+0

請參閱我編輯的答案的樣本。 – Harry