Данные испытаний:
declare @tbl table (ID int, PickupDateTime datetime2(3), Amount2 int)
insert into @tbl values
(1, '2019-04-02 04:44:19.000', 6458),
(1, '2019-04-02 04:31:02.000', 5385),
(1, '2019-04-02 01:56:12.000', 1545),
(1, '2019-04-01 07:49:54.000', 3466),
(1, '2019-03-31 05:26:03.000', 7505),
(1, '2019-03-31 05:12:10.000', 5080),
(1, '2019-03-31 01:43:52.000', 1166),
(1, '2019-03-30 07:41:03.000', 2991),
(1, '2019-03-29 05:01:14.000', 7065),
(2, '2019-04-01 04:56:21.000', 9518),
(2, '2019-03-30 05:04:00.000', 9638),
(2, '2019-03-28 04:29:31.000', 9499),
(2, '2019-03-26 05:00:44.000', 10117),
(2, '2019-03-24 04:57:03.000', 9933),
(2, '2019-03-22 05:06:57.000', 9869);
Запрос, чтобы получить желаемые результаты. Ключ заключается в использовании подзапросов с соответствующими предложениями where
:
select t1.*,
(select count(*) from @tbl t2
where dateadd(hour, -18, t1.pickupdatetime) <= t2.PickupDateTime
and t1.PickupDateTime >= t2.PickupDateTime
and t1.id = t2.id) Rows_18,
(select sum(Amount2) from @tbl t2
where dateadd(hour, -18, t1.pickupdatetime) <= t2.PickupDateTime
and t1.PickupDateTime >= t2.PickupDateTime
and t1.id = t2.id) Amount2_18,
(select count(*) from @tbl t2
where dateadd(hour, -22, t1.pickupdatetime) <= t2.PickupDateTime
and t1.PickupDateTime >= t2.PickupDateTime
and t1.id = t2.id) Rows_22,
(select sum(Amount2) from @tbl t2
where dateadd(hour, -22, t1.pickupdatetime) <= t2.PickupDateTime
and t1.PickupDateTime >= t2.PickupDateTime
and t1.id = t2.id) Amount2_22
from @tbl t1
order by t1.PickupDateTime desc