SQL每小时​​数据计算日期范围

时间:2015-01-16 15:14:20

标签: sql sql-server

SQLSERVER 2012:

SQL Query返回小时数从0到23开始的24小时数据。正在处理的查询是,当您选择日期范围时,例如“1-1-2014”和“1-2-2014”时,报告应该在上午9点到次日上午8点获取数据。

查询应该计算我们选择的任何日期范围,但应该只选择从第二天/月/年的上午9点到早上8点的小时数。

表格结构/列我在DB中: ReadingDate 营业时间:0-23 数据1 数据2 数据3

输出

Date    |       Hours|         Data 1|       Data 2|     Data 3

sSelect = "Select P.ReadingDate,P.Hour,P.Data1,P.Data2,P.Data3 FROM Operations P WHERE P.ReadingDate = '" & startdate & "' AND P.Hour Between 9 AND 23 Group by P.ReadingDate,P.Hour,P.Data1,P.Data2,P.Data3
Union 
Select P.ReadingDate,P.Hour,P.Data1,P.Data2,P.Data3 FROM Operations P WHERE P.ReadingDate = '" & Enddate & " ' AND P.Hour Between 0 And 8 group by P.ReadingDate,P.Hour,P.Data1,P.Data2,P.Data3 "

2015-1-15 12:00 AM|      9| 1900|2000|300
2015-1-15 12:00 AM|     10|
2015-1-15 12:00 AM|     11|
2015-1-15 12:00 AM|     12|
2015-1-15 12:00 AM|     13|
2015-1-15 12:00 AM|     14|
2015-1-15 12:00 AM|     15|
2015-1-15 12:00 AM|     16|
2015-1-15 12:00 AM|     17|
2015-1-15 12:00 AM|     18|
2015-1-15 12:00 AM|     19|
2015-1-15 12:00 AM|     20|
2015-1-15 12:00 AM|     21|
2015-1-15 12:00 AM|     22|
2015-1-15 12:00 AM|     23|
2015-1-16 12:00 AM|      0|
2015-1-16 12:00 AM|      1|
2015-1-16 12:00 AM|      2|
2015-1-16 12:00 AM|      3|
2015-1-16 12:00 AM|      4|
2015-1-16 12:00 AM|      5|
2015-1-16 12:00 AM|      6|
2015-1-16 12:00 AM|      7|
2015-1-16 12:00 AM|      8|

我能够获取日期范围'1-1-2015'和'1-2-2015'的1天数据,但如果我选择月'12 -1-2014'到12-的日期范围31-2014'它没有给我全部数据,它再次得到了我1天的数据。

1 个答案:

答案 0 :(得分:0)

这是在考虑SQL Server的情况下完成的:

DECLARE @BeginDate datetime = '2014-01-01';     --List only as a starting date; do not include the time
DECLARE @EndDate datetime = '2014-01-02';       --List only as a end date; do not include the time; should not be the same as @BeginDate;
                                                --Could change this to expect the same date, but will need to add a full day to @EndDate below in addition to hour
SET @BeginDate = DATEADD(HOUR, 9, @BeginDate);  --Sets the starting time at 9:00 AM per business rules
SET @EndDate = DATEADD(HOUR, 8, @EndDate);      --Sets the ending time at 8:00 AM per business rules

SELECT
    YourTable.ReadingDate,
    YourTable.Hours,
    YourTable.Data1,
    YourTable.Data2,
    YourTable.Data3
FROM
    YourTable
WHERE
    DATEADD(HOUR, YourTable.Hours, YourTable.ReadingDate) BETWEEN @BeginDate AND @EndDate;