Skip to content
Advertisement

Pulling out monthly daypart data

I’m dealing with sales data that looks like this

Date Time Net Amount Store No Item Category Code
2021-03-21 00:00:00.000 1754-01-01 08:01:14.627 100 001 FOOD
2021-01-31 00:00:00.000 1754-01-01 15:42:21.670 120 002 FOOD
2021-04-24 00:00:00.000 1754-01-01 17:35:30.070 160 002 FOOD
2021-03-14 00:00:00.000 1754-01-01 13:08:02.073 150 003 FOOD
2021-02-27 00:00:00.000 1754-01-01 18:33:53.847 95 001 FOOD
2021-02-20 00:00:00.000 1754-01-01 21:30:24.007 180 002 DRINK
2021-04-09 00:00:00.000 1754-01-01 07:36:33.930 110 003 FOOD
2021-01-29 00:00:00.000 1754-01-01 08:02:49.703 180 002 FOOD
2021-01-24 00:00:00.000 1754-01-01 11:01:00.953 110 003 FOOD

What I need is to pull out monthly data by daypart that would result to this

Jan 2021 Feb 2021 Mar 2021 Apr 2021
4am to 10:59am 180 0 100 110
11am to 1:59pm 110 0 150 0
2pm to 3:59am 120 95 0 160

Here’s the query I’m currently using:

I’ve also tried using

but when both are tried with another interval, the sales amount just comes out the same.

Advertisement

Answer

I would suggest to you to store time as part of datetime column itself. If you want to keep time separately, store them in the time datatype. I have put sample below considering both date and time being stored in the date column.

You can use DATEPART to demarcate the time ranges and then use pivot to generate result set as given below:

timerange Mar 21 Apr 21
4am to 10:59am 100 160
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement