I am trying to write a query based on datetime and weekday in sql server where my output should be like :
My table descriptions are:
**Branch**(DateKey integer,
BranchName varchar2(20),
TransactionDate datetime,
OrderCount integer)
**Date**(DateKey integer PrimaryKey,
DayNameofWeek varchar2(15))
This is the raw data I have
So, this is quite a long shot but I solved it the following way:
I created a
table valued function
, which would take adate
as a parameter and find all15-minute
intervals during that day. For each day it would go from00:00, to 00:15, 00:30
up to23:30, 23:45
, and23:59
. It also returns each intervalstart time
andend time
, since we will need to use this for every row in yourbranch
table to check if they fall into that time slot and if so, count it in.This is the function:
Then, I am querying your
branch
table (you don't really need theDate
table, the weekday now you have it in the function but even if not, there's a DATENAME function in SQL Server, starting with 2008 that you can use.I would query your table like this:
Please note I have used in the
PIVOT
function only the intervals I can see in the image you posted, but of course you could write all15-minute
intervals of the day manually - you would just need to write them once in thepivot
and once in theselect
statement - or optionally, generate this statementdynamically
.