SQL查询未给出预期答案
SELECT CAST(PR.DateTimeStamp as date) AS PRDate,COUNT(PR.ID) AS PRCount
FROM tbl_Purchase PR
INNER JOIN tbl_PurchaseCategory PTC ON PR.ID = PTC.ID
WHERE PR.DateTimeStamp BETWEEN DATEADD(DAY,-30,'2017-12-07 09:00:00') AND
'2017-12-07 09:00:00' and PR.DepartmentID=1 and PTC.CategoryID=1 group by
CAST(PR.DateTimeStamp as date) order by CAST(PR.DateTimeStamp as date)
我想选择像
这样的数据PRDate PRCount
2017-12-07 3 // from 2017-12-08 09:00:00 to 2017-12-07 09:00:00
2017-12-06 31 // from 2017-12-07 09:00:00 to 2017-12-06 09:00:00
2017-12-05 10 // from 2017-12-06 09:00:00 to 2017-12-05 09:00:00
2017-12-04 23
2017-12-03 27
2017-12-02 15
2017-12-01 27
2017-11-30 39
2017-11-29 25
2017-11-28 27
2017-11-27 36
2017-11-26 30
2017-11-25 23
2017-11-24 18
2017-11-23 13
2017-11-22 16
2017-11-21 25
2017-11-20 15
2017-11-19 41
2017-11-18 11
2017-11-17 9
2017-11-16 19
2017-11-15 23
2017-11-14 17
2017-11-13 23
2017-11-12 20
2017-11-11 31
2017-11-10 29
2017-11-09 18
2017-11-08 29
2017-11-07 24
以上查询证明了我的数据
12到12时间间隔而不是9到9
答案 0 :(得分:1)
您应该从该组的日期减去9小时。
SELECT
CAST( DATEADD(HOUR,-9, PR.DateTimeStamp) as date) AS PRDate
, COUNT(PR.ID) AS PRCount
FROM tbl_Purchase PR
INNER JOIN tbl_PurchaseCategory PTC ON PR.ID = PTC.ID
WHERE
PR.DateTimeStamp BETWEEN DATEADD(DAY,-30,'2017-12-07 09:00:00') AND '2017-12-07 09:00:00'
AND PR.DepartmentID=1 and PTC.CategoryID=1
group by
CAST(DATEADD(HOUR,-9, PR.DateTimeStamp) as date)
order by
CAST(DATEADD(HOUR,-9, PR.DateTimeStamp) as date)