Skip to content
Advertisement

Count rows within date range with condition

I’m not sure that this issue can be solved in SQL server, but I decided to ask you anyway.

Let’s create a table and add some random variables:

Now, let’s add to the table two columns:

  • “before_5” – five minutes before the given timestamp
  • “after_5” – five minutes the given timestamp

Now our table looks in the following way:

timestamp product client_id seconds before_5 after_5
2022-08-05 07:14:59.000 A 11 1 2022-08-05 07:09:59 2022-08-05 07:19:59
2022-08-05 07:14:59.000 A 11 1 2022-08-05 07:09:59 2022-08-05 07:19:59

The task is the following: If the the value in the column “seconds”>=8, then I need to count the number of the same products within the range (5 minutes before and 5 minutes after) of this row.

I want to receive the following results:

timestamp product client_id seconds num_of_products
2022-08-05 07:17:50.000 A 11 10 5
2022-08-05 08:17:55.000 B 5 12 4

Also, I’m attaching screenshot:

enter image description here

Advertisement

Answer

A simple correlated subquery should give you your expected results.

It’s not clear if you’re expecting to filter the results to only rows with seconds >=8 however if that’s the case the query just needs a where criteria and removal of the case expression:

Note that datetime was deprecated years ago by datetime2 and varchar(max) should be avoided if your product names are not potentially > 8kb in length.

See DB<>Fiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement