从时间戳创建日期范围

时间:2014-07-07 18:44:46

标签: sql-server

下面的查询将Time_Stamp列中的最大日期从Survey中删除为StartDate。为EndDate添加90天。然后通过向原始EndDate添加更多内容,再创建另外两个范围,间隔为90天。

我试图让StartDate落在Jan1st,April1st,July1st或Oct1的4个桶中。如果Max Time_Stamp在这些日期中的1个之前,则那将是我的范围的第一个StartDate ...因此,对于我的示例,最大Time_Stamp是6月4日,因此StartDate需要是7月1日。这在sql server中是否可行?

Hospital1的Time_Stamp

Time_Stamp
-----------
2014-06-04 16:01:14.000
2014-06-04 15:55:33.000
2014-06-04 15:45:05.000
2014-06-04 15:36:15.000
2014-06-04 15:00:34.000
2014-06-04 14:35:24.000
2014-06-04 14:04:50.000
2014-06-04 13:46:55.000
2014-06-04 13:23:57.000
2014-06-04 11:27:51.000

当前输出:

StartDate   EndDate
----------- -----------
Jun  4 2014 Sep  2 2014
Sep  3 2014 Dec  2 2014
Dec  3 2014 Mar  3 2015

查询

WITH Start AS
(
    SELECT 
           MAX(Time_Stamp) as StartDate, 
           DATEADD(day, 90, MAX(Time_Stamp)) as EndDate
    FROM Survey
    WHERE MainHospital = 'Hospital1'

),
Results AS
(
   SELECT StartDate, EndDate from Start
   UNION
   SELECT DATEADD(DAY, 1, EndDate), DATEADD(day, 91, EndDate) FROM Start
   UNION
   SELECT DATEADD(DAY, 92, EndDate), DATEADD(day, 182, EndDate) FROM Start
)
SELECT LEFT(StartDate,11) AS StartDate, LEFT(EndDate,11) AS EndDate FROM Results

只是一个更新,这给了我第一个StartDate所需要的东西......

    --Return first day of next quarter
SELECT DATEADD(qq, DATEDIFF(qq, 0, MAX(Time_Stamp)) + 1, 0)
FROM Survey
WHERE MainHospital = 'Hospital1'

3 个答案:

答案 0 :(得分:1)

DECLARE @Year DATE = '2013-01-01'
DECLARE @Quarter INT = 1;

SELECT  DATEADD(QUARTER, @Quarter - 1, @Year) ,
        DATEADD(DAY, -1, DATEADD(QUARTER,  @Quarter, @Year))

您可以使用DATEPART(QUARTER,@ Date)来确定所选记录的四分之一,然后您可以使用此查询来查找该季度的开始/结束日期。

像这样使用:

SELECT  DATEADD(QUARTER, DATEPART(QUARTER, Time_Stamp) - 2, DATEADD(YEAR, DATEDIFF(YEAR, 0, Time_Stamp), 0)) AS StartDate,
        DATEADD(SECOND, -1, DATEADD(QUARTER,  DATEPART(QUARTER, Time_Stamp) - 1, DATEADD(YEAR, DATEDIFF(YEAR, 0, Time_Stamp), 0))) AS EndDate
FROM Hospital1

答案 1 :(得分:0)

您似乎只是想计算日期的四分之一,我是否正确?

如果是这样,你可以使用:

SELECT DATENAME(Quarter, CAST(CONVERT(VARCHAR(8), GETDATE()) AS DATETIME)) as Quarter

答案 2 :(得分:0)

计算季度日期范围:

select DATEADD(qq, datediff(qq, 0, getdate()),0) as first

select dateadd(dd, -1, DATEADD(qq, datediff(qq, 0, getdate()) +1, 0)) as last