在SQL Server中明智地拆分数据日期时间

时间:2016-02-10 03:21:57

标签: sql sql-server sql-server-2008

我要求将数据从今天上午8:00到第二天上午7:59按天分组为一整天。

例如,从下表:

SoldDatetime           Qty
Dec 20,2015 12:05 AM    1
Dec 20,2015 1:05 AM     2
Dec 20,2015 7:05 AM     3
Dec 20,2015 8:05 AM     4
Dec 20,2015 10:05 AM    5
Dec 20,2015 11:05 PM    6
Dec 21,2015 12:05 AM    7
Dec 21,2015 1:05 AM     8
Dec 21,2015 7:05 AM     9
Dec 21,2015 8:05 AM     10
Dec 21,2015 10:05 AM    11
Dec 21,2015 11:05 PM    12
Dec 22,2015 12:05 AM    13
Dec 22,2015 1:05 AM     14
Dec 22,2015 7:05 AM     15
Dec 22,2015 8:05 AM     16
Dec 22,2015 10:05 AM    17
Dec 22,2015 11:05 PM    18
Dec 23,2015 12:05 AM    19
Dec 23,2015 1:05 AM     20
Dec 23,2015 7:05 AM     21
Dec 23,2015 8:05 AM     22
Dec 23,2015 10:05 AM    23
Dec 23,2015 11:05 PM    24
Dec 24,2015 12:05 AM    25
Dec 24,2015 1:05 AM     26
Dec 24,2015 7:05 AM     27
Dec 24,2015 8:05 AM     28
Dec 24,2015 10:05 AM    29
Dec 24,2015 11:05 PM    30
Dec 25,2015 12:05 AM    31
Dec 25,2015 1:05 AM     32
Dec 25,2015 7:05 AM     33
Dec 25,2015 8:05 AM     34
Dec 25,2015 10:05 AM    35
Dec 25,2015 11:05 PM    36

如果我必须运行查询来过滤日期范围Dec 21,2015 8:00 AM到Dec 25,2015 7:59 AM。我需要以下格式输出

SoldDateRange                               Qty
Dec 20,2015 8:00 AM - Dec 21,2015 7:59AM    39
Dec 21,2015 8:00 AM - Dec 22,2015 7:59AM    75
Dec 22,2015 8:00 AM - Dec 23,2015 7:59AM    111
Dec 23,2015 8:00 AM - Dec 24,2015 7:59AM    147
Dec 24,2015 8:00 AM - Dec 25,2015 7:59AM    183

有人可以帮助SQL查询吗?提前致谢

2 个答案:

答案 0 :(得分:1)

这是一个查询,它可以为您提供原始问题中提到的完整输出。

SELECT CONCAT(CONVERT(VARCHAR, t.adjustedTime, 107), ' 8:00 AM',
              ' - ',
              CONVERT(VARCHAR, DATEADD(DAY, 1, t.adjustedTime), 107), ' 7:59AM'),
       t.Qty
FROM
(
    SELECT CAST(DATEADD(HOUR, -8, SoldDateTime) AS DATE) AS adjustedTime, SUM(Qty) AS Qty
    FROM yourTable
    GROUP BY CAST(DATEADD(HOUR, -8, SoldDateTime) AS DATE)
) t
ORDER BY t.adjustedTime

答案 1 :(得分:0)

您可以通过减去8小时来完成此操作。基本思路是:

select cast(dateadd(hour, -8, solddaterange) as date) as SoldDate, sum(qty)
from t
group by cast(dateadd(hour, -8, solddaterange) as date)
order by SoldDate;

编辑:

您可以使用相同的想法。例如:

where cast(dateadd(hour, -8, solddaterange) as date) = '2016-01-01'