一周特定小时部分的数据总和 - MS SQL查询

时间:2018-03-04 07:44:02

标签: sql-server sql-server-2014 datepart

为了找到一周的数据总和(在我的情况下是CallsAnswered),但是在下午6点到12点之间找到特定的小时数,我在下面设置了一个查询,但它正在跳过我的一天数据样本数据。您可以验证我的查询并帮助我找到我失踪的地方吗?

创建查询:

Create Table tblSingleBox (ScanDate DateTime, SkillTargetID Varchar(10), CallsAnswered int)

插入查询

Insert into tblSingleBox 
Values ('2018-02-18 19:17:01', '10888', 32),
('2018-02-18 23:59:59', '10888', 01),
('2018-02-19 00:10:01', '10888', 15),
('2018-02-19 17:59:59', '10889', 12),
('2018-02-19 20:59:59', '10889', 90),
('2018-02-25 21:59:59', '10889', 40)

查询:

SELECT convert(varchar(10),ScanDate,101)ScanDate,SkillTargetID, SUM(CallsAnswered)CallsAnswered
FROM    tblSingleBox (nolock)
WHERE    DATEPART(Hour, scandate) between 18 and 24
    and (scandate between '2018-02-18' and '2018-02-25')
GROUP BY    convert(varchar(10),ScanDate,101) ,SkillTargetID
order by convert(varchar(10),ScanDate,101)

预期输出:

ScanDate    SkillTargetID   CallsAnswered
18-02-2018  10888   33
18-02-2018  10889   11
19-02-2018  10889   90
25-02-2018  10889   40

实际输出我得到了:

ScanDate    SkillTargetID   CallsAnswered
02/18/2018  10888   33
02/18/2018  10889   11
02/19/2018  10889   90

1 个答案:

答案 0 :(得分:2)

scandate有时间且2018-02-25 21:59:59大于2018-02-25(与DATETIME相比时被视为2018-02-25 00:00:00。)

scandate投射到DATE(截止时间)或更改

scandate between '2018-02-18' and '2018-02-25'

scandate >= '2018-02-18' and scandate < '2018-02-26'