我不擅长处理SQL中的日期。我希望在SQL Server中的两个日期之间获得完整和部分日期时段。
更多解释。
例如,我的日期范围如下:
StartDate - '2017-07-26 10:30:00'
End Date - '2017-07-29 16:45:00'
我想填充下面的时段。
slot 1 - 2017-07-26 10:30:00 - 2017-07-26 23:59:00
slot 2 - 2017-07-27 00:00:00 - 2017-07-27 23:59:00
slot 3 - 2017-07-28 00:00:00 - 2017-07-28 23:59:00
slot 4 - 2017-07-29 00:00:00 - 2017-07-29 16:45:00
26日和29日不是完整的日子。
有没有人知道如何在SQL Server中实现这一目标?我可以使用循环并执行此操作,但会出现性能问题。我尝试使用递归CTE,但它没有用。
提前致谢。 :)
答案 0 :(得分:1)
这可以使用 calendar 表轻松完成。以下是一种使用Recursive CTE
生成日期的方法
DECLARE @StartDate DATETIME = '2017-07-26 10:30:00',
@EndDate DATETIME = '2017-07-29 16:45:00';
WITH cte
AS (SELECT @StartDate st
UNION ALL
SELECT Cast(Cast(Dateadd(dd, 1, st) AS DATE) AS DATETIME)
FROM cte
WHERE st < CAST(@enddate AS DATE))
SELECT st,
CASE
WHEN @EndDate < Dateadd(mi, -1, Cast(Dateadd(dd, 1, Cast(st AS DATE)) AS DATETIME)) THEN @EndDate
ELSE Dateadd(mi, -1, Cast(Dateadd(dd, 1, Cast(st AS DATE)) AS DATETIME) )
END AS ed
FROM cte
我建议您创建一个物理日历表来执行此操作。
答案 1 :(得分:1)
您可以使用以下CTE:
输出如下:<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="test.saveinstance.MainActivity"> <EditText android:id="@+id/withId" android:layout_marginTop="30dp" android:layout_width="match_parent" android:layout_height="70dp" android:gravity="center" android:hint="Type Here (has android:id)" /> <EditText android:layout_below="@id/withId" android:layout_marginTop="20dp" android:layout_width="match_parent" android:layout_height="70dp" android:gravity="center" android:hint="Type Here (doesn't have android:id)" /> <Button android:id="@+id/button" android:layout_alignParentBottom="true" android:layout_marginBottom="10dp" android:text="Click Me" android:layout_width="match_parent" android:layout_height="50dp" /> <Button android:id="@+id/save" android:layout_above="@id/button" android:layout_marginBottom="10dp" android:text="Save" android:layout_width="match_parent" android:layout_height="50dp" /> </RelativeLayout>
Declare @StartDate datetime = '2017-07-26 10:30:00' Declare @EndDate datetime = '2017-07-29 16:45:00'
;with Cte_dates as (
Select dateadd(dd,1,Datediff(dd,0,@StartDate)) as StDate
Union All
Select DATEADD(dd,1, StDate) from Cte_dates where StDate < DAteADd(dd, -2, @endDate)
)
Select @StartDate as StartSlot, DateAdd(mi, -1,dateadd(dd,1,Datediff(dd,0,@StartDate))) as EndSlot
Union all
Select StDate as StartSlot,Dateadd(mi,-1, dateadd(dd,1,stDate)) EndSlot from Cte_dates --Generates from CTE for in between slots
Union all
Select Dateadd(dd,0,Datediff(dd,0,@EndDate)) as StartSlot, @EndDate as EndSlot