linq to sql将日期合并为组

时间:2012-06-20 11:23:38

标签: tsql sql-server-2005 linq-to-sql

我有一个简单的SQL查询,如下所示:

SELECT dt AS 'startDate'
 , dt AS 'endDate'
FROM
    WorkCalendar
WHERE
     dt BETWEEN dateadd(yy, datediff(yy, 0, getdate()), 0) AND dateadd(MILLISECOND, -3, dateadd(YEAR, datediff(YEAR, 0, getdate()) + 1, 0))
     AND isWorkDay = 0

这将返回我的表中包含当年无工作日的所有日期。

这是示例输出:

startDate               endDate
2012-01-01 00:00:00     2012-01-01 00:00:00
2012-01-06 00:00:00     2012-01-06 00:00:00
2012-01-07 00:00:00     2012-01-07 00:00:00
2012-01-08 00:00:00     2012-01-08 00:00:00
2012-01-14 00:00:00     2012-01-14 00:00:00
2012-01-15 00:00:00     2012-01-15 00:00:00
2012-01-21 00:00:00     2012-01-21 00:00:00
2012-01-22 00:00:00     2012-01-22 00:00:00

我想做的是将近日期分组:

startDate               endDate
2012-01-01 00:00:00     2012-01-01 00:00:00
2012-01-06 00:00:00     2012-01-08 00:00:00
2012-01-14 00:00:00     2012-01-15 00:00:00
2012-01-21 00:00:00     2012-01-22 00:00:00

如果我有两天或更多天,我想将他们加入小组。

我想用linq to sql完成,因为在webservice中使用它会更简单,但是简单的sql会起到作用:)

1 个答案:

答案 0 :(得分:0)

得到这样的东西:

WITH d (d1) 
 AS (SELECT dt 
     FROM   workcalendar 
     WHERE  dt BETWEEN Dateadd(yy, Datediff(yy, 0, Getdate()), 0) AND 
                               Dateadd(millisecond, -3, 
                               Dateadd(year, Datediff(year, 
                                             0, 
                                             Getdate()) + 1 
                               , 0)) 
            AND isworkday = 0) 
SELECT Z1.d1 AS startDate, 
   Z2.d1 AS endDate 
FROM   (SELECT Row_number() 
             OVER ( 
               ORDER BY A.d1) AS 'ID', 
           A.d1 
    FROM   d AS A 
    WHERE  NOT EXISTS (SELECT * 
                       FROM   d AS C 
                       WHERE  A.d1 = Dateadd(d, 1, C.d1))) AS Z1, 
   (SELECT Row_number() 
             OVER ( 
               ORDER BY A.d1) AS 'ID', 
           A.d1 
    FROM   d AS A 
    WHERE  NOT EXISTS (SELECT * 
                       FROM   d AS C 
                       WHERE  A.d1 = Dateadd(d, -1, C.d1))) AS Z2 
WHERE  Z1.id = Z2.id  

但欢迎任何评论和优化:)