Structuring Date for Period Over Period

Problem:

A very common request is one in which someone wants to see a current time period metric in comparison to a previous time period metric such as by week, month, quarter, or year. In the past, this has been accomplished with a query in which a series of JOIN operations would have to be employed inside the query.

Issue:

Having to write queries with JOIN operations leads to large and complicated queries that can be very time consuming to complete.

Resolution:

SQL Server 2012 has many new functions including ‘LAG’ & ‘LEAD’. These two functions significantly simplify the query writing process and can, in some cases, remove the need for the JOIN operation.

By using the new LAG and LEAD functions, the amount of time that the query takes to write can be decreased dramatically.

Example:

Image 1 shows an example table being used to populate the chart. The table contains Sales, Units, and COGs by Product Line and Date for approximately a year.

Image 1

Image 2 shows the query on the table with the LAG function and the result set below that. Please notice in the highlighted areas in the image that the metrics PP Sales, PP Units, and PP COGs for Accessories Week 2 match the values CP Sales, CP Units, and CP COGs for Accessories Week 1. CP = Current Period & PP = Previous Period.