Skip to content
Advertisement

TSQL – Compare two columns with self join – Calculate the difference between yesterdays total’s and today’s total

I’m trying to calculate the difference between today’s and yesterday’s totals on a column. If a self join isn’t the best way to do that, that is fine, whichever will give me the result I’m after should be ok.

Requirements:

  1. Only compare the last 2 days worth of data, even though the table will have multiple days worth of data, only one entry per day though.
  2. Calculate the difference between yesterdays totals and today’s totals for the column.

Problem

The code below returns a zero and I’m not understanding why.

Why won’t it calculate and what should I do to meet the requirements please?


Advertisement

Answer

I think you want lag():

If you want only the last two days, then:

Note: This interprets “yesterday” as the last two days in the table. If you actually want today and yesterday specifically, then you can use a where clause:

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