;WITH t AS(
SELECT 1 AS userID, '2014-01-08 00:00:00' AS startDate, '2014-01-08 12:00:00' AS endDate UNION ALL
SELECT 1 AS userID, '2014-01-08 13:00:00' AS startDate, '2014-01-12 00:00:00' AS endDate UNION ALL
SELECT 1 AS userID, '2014-01-13 00:00:00' AS startDate, '2014-01-19 00:00:00' AS endDate UNION ALL
SELECT 1 AS userID, '2014-01-20 00:00:00' AS startDate, '2014-01-22 00:00:00' AS endDate UNION ALL
SELECT 2 AS userID, '2014-01-08 00:00:00' AS startDate, '2014-01-08 12:00:00' AS endDate
)
SELECT * FROM t
/*
* 想要如下结果
* userID startDate endDate
----------- ------------------- -------------------
1 2014-01-08 00:00:00 2014-01-08 12:00:00
1 2014-01-08 13:00:00 2014-01-22 00:00:00
2 2014-01-08 00:00:00 2014-01-08 12:00:00
*/
------解决方案--------------------
怎么算是跨周,为什么不是从'2014-01-08 00:00:00' 而是从'2014-01-08 13:00:00' 算
------解决方案--------------------
楼主先要说明你的数据的筛选方法,夸周是什么意思?而不是让大家去猜
------解决方案--------------------
如果这样那就要改设计了,不然没法查,因为你根本无法区分哪几条数据是由于跨周而拆分插入的数据
------解决方案--------------------
第一条记录为什么不合并?
------解决方案--------------------
;WITH t AS(
SELECT 1 AS userID, '2014-01-08 00:00:00' AS startDate, '2014-01-08 12:00:00' AS endDate UNION ALL
SELECT 1 AS userID, '2014-01-08 13:00:00' AS startDate, '2014-01-12 00:00:00' AS endDate UNION ALL
SELECT 1 AS userID, '2014-01-13 00:00:00' AS startDate, '2014-01-19 00:00:00' AS endDate UNION ALL
SELECT 1 AS userID, '2014-01-20 00:00:00' AS startDate, '2014-01-22 00:00:00' AS endDate UNION ALL
SELECT 2 AS userID, '2014-01-08 00:00:00' AS startDate, '2014-01-08 12:00:00' AS endDate
),
t1 as(
select dateadd(day,7,min(startdate)) as mindate from t as b
)
SELECT * FROM t
where enddate <=(select mindate from t1 )
--结果展示
/*
userID startDate endDate
----------- ------------------- -------------------
1 2014-01-08 00:00:00 2014-01-08 12:00:00
1 2014-01-08 13:00:00 2014-01-12 00:00:00
2 2014-01-08 00:00:00 2014-01-08 12:00:00
(3 行受影响)
*/
------解决方案--------------------
怎么不对
------解决方案--------------------
这是设计的问题。
方案A
原始数据拆分前先分配一个唯一的id,这个id写入记录,那么查询时就能按id合并不用猜了。
方案B
最好是原始数据另外开一个表,留下记录。
那么要查拆分前的就查原始表,要查拆分后的就查拆分表。毫无压力。
当然拆分表最好还是添上原始记录的id,这样有关联,可能某些查询会用到。
------解决方案--------------------
说个查询方式:把全部时间范围内的所有周的 周6零点到周日24点这个范围作为一条记录,全部union all 进去,相当于加个N多时间段,然后,再取连续时间。即可。
当然查询结果还要再加工,比如结果如果开始时间或者结束时间是周末时间段,那么要掐头去尾。
懒得写了。