需要帮助找到正确的T-SQL查询

时间:2011-05-23 15:20:33

标签: sql sql-server sql-server-2005 tsql gaps-and-islands

我不太清楚该怎么做。基本上我有这样的表

UserId       DateRequested           Approved ApprovedBy  Notes
------------ ----------------------- -------- ----------- -----
1            2011-05-26               0        NULL        NULL
1            2011-05-27               0        NULL        NULL
1            2011-05-28               0        NULL        NULL
1            2011-06-05               0        NULL        NULL
1            2011-06-06               0        NULL        NULL
1            2011-06-25               0        NULL        NULL

其中基本上包含员工请求假期的日期。现在,当授予一天或几天时,需要将此数据复制到表格

的表格中
UserId DateFrom DateTo

所以基本上我想要的上述数据:

UserId DateFrom DateTo 
-------------------------------
1      2011-05-26 2011-05-28 
1      2011-06-05 2011-06-06 
1      2011-06-25 2011-06-25 

即我想在DateFrom和DateTo连续几天。现在我不知道如何在不使用while循环的情况下执行此操作。这是SQL,所以我更喜欢非迭代的解决方案。

请指教!!!

2 个答案:

答案 0 :(得分:6)

;WITH cte AS
(
SELECT *,
        DATEDIFF(DAY,0,DateRequested)-
        ROW_NUMBER() OVER (PARTITION BY UserId ORDER BY DateRequested) AS Grp
FROM YourTable  
WHERE Approved = 1 /*Presumably - but your example data doesn't show this.*/
)
SELECT UserId, 
       MIN(DateRequested) AS DateFrom, 
       MAX(DateRequested) AS DateTo  
FROM cte 
GROUP BY UserId,Grp

答案 1 :(得分:1)

在Oracle PL / SQL中,它将编写如下:

WITH cte
        AS (SELECT a.*,
                   daterequested - TRUNC (SYSDATE)
                   - ROW_NUMBER ()
                        OVER (PARTITION BY UserId ORDER BY DateRequested)
                      AS Grp
              FROM yourtable a
             WHERE Approved = 0)
  SELECT UserId, MIN (DateRequested) AS DateFrom, MAX (DateRequested) AS DateTo
    FROM cte
GROUP BY UserId, Grp;