sql query问题:默认情况下至少获得一列

时间:2014-05-11 07:52:49

标签: sql stored-procedures stored-functions

我通过参数 @UserId_Fk 获取表格数据。 如果 @UserId_Fk 等于2,则结果正确。 如果它是3或任何其他,我得到的结果是正确的,但有一个 UserId_Fk 2的顶行。

表格结构:

TestId  int 
UserId_Fk   int  
CheckInTime datetime 
LoginStatus char(1) 

示例数据:

  Id     UserId_Fk        CheckInTime        LoginStatus
   1    2   2013-01-01 12:00:00.000      I
   2    2   2013-12-22 13:01:01.000      O
   3    2   2013-12-22 13:49:54.000      I
   4    2   2013-12-22 13:49:55.000      I
   5    2   2013-12-22 15:58:42.000      O
   6    3   2013-12-23 06:02:58.000      I
   7    3   2013-12-23 14:00:29.000      O
   8    3   2013-12-24 05:17:09.000      I
   9    3   2013-12-24 12:34:25.000      O
   10   3   2013-12-24 12:34:26.000      O 

这是我的存储过程来获取表

createproc [dbo].[GetCheckInCheckOutTable]
   @UserId_Fk  int

   as
   begin
   SELECT 
  t.UserId_Fk
, [Date] = DATEADD(dd, 0, DATEDIFF(dd, 0, t.CheckIn))
, CheckIn = CONVERT(VARCHAR(10), t.CheckIn, 108)
, CheckOut = CONVERT(VARCHAR(10), t.CheckOut, 108)
, [Hours] = CAST(DATEDIFF(MINUTE, t.CheckIn, t.CheckOut) / 60. AS DECIMAL(10,2))
FROM (
SELECT 
      t.UserId_Fk
    , CheckIn = t.CheckInTime
    , CheckOut = r.CheckInTime
    , RowNum = ROW_NUMBER() OVER (PARTITION BY t.UserId_Fk, r.CheckInTime ORDER BY 1/0)
FROM UserTime t
OUTER APPLY (
    SELECT TOP 1 *
    FROM UserTime t2
    WHERE t2.UserId_Fk = t.@UserId_Fk
        AND t2.CheckInTime > t.CheckInTime
        AND DATEADD(dd, 0, DATEDIFF(dd, 0, t.CheckInTime)) = DATEADD(dd, 0, DATEDIFF(dd, 0, t2.CheckInTime))
        AND t2.LoginStatus = 'O'
    ORDER BY t2.CheckInTime
) r
WHERE t.LoginStatus = 'I'
) t
WHERE t.RowNum = 1
end

0 个答案:

没有答案