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

[英]Need help finding the correct T-SQL Query


I am not quite sure how to go about doing this. Basically I have have a table like this

我不太清楚该怎么做。基本上我有一张这样的桌子

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

Which basically contains the days an employee requests a holiday. Now, when a day or days is granted, this data needs to be copied over to a table of the form

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

UserId DateFrom DateTo

So basically for the above data i want:

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

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

I.e I want consecutive days in the DateFrom and DateTo. Now I am not sure how to do this without using a while loop. This is SQL, So i would prefer a non-iterative solution.

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

Please advise!!!

请指教!!!

2 个解决方案

#1


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

#2


1  

In Oracle PL/SQL it would be written as follows:

在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;

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2011/05/23/c4562d9b4067eab86040abd1d0e2e268.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号