SQL server, SQLServerPedia Syndication

Breaking down dates using DATEPART.

You may have written ad-hoc queries to pull data for a certain date range. As this report gets popular over time and the date range expands, you may be asked to do a break down of the report. For example: per month or querter.

The magical function that helps with this purpose is the DATEPART function. With the DATEPART function, you can extract (otherwise tricky) calendar references like quarter, month, week, weekday, etc without having to guess the correct condition in your where clause.

Below is an example of how this function is used to break down a yearly report into quarters.

SELECT subq1.QuarterPart, sum(subq1.OrderPrice) from
CASE DATEPART(quarter, OrderCompletedDate)
    when 1 then ‘Q1’
    when 2 then ‘Q2’
    when 3 then ‘Q3’
    when 4 then ‘Q4’
end as QuarterPart
from Orders where OrderCompletedDate BETWEEN ‘2012-01-01’ AND ‘2013-01-01’
GROUP by subq1.QuarterPart
order by subq1.QuarterPart asc

Compare this with having to figure out and write where clauses like: ” where OrderCompletedDate >= ‘2012-01-01’ and OrderCompletedDate < ‘2012-04-01’ “. Now imagine doing this for a weekly breakdown.


Thinking about someting? Leave a Reply...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s