Skip to content
Advertisement

How to calculate the slope in SQL

I have some data in a sql database and I’d like to calculate the slope. The data has this layout:

I’d like the final output to look like this by creating a new table using SQL:

To complicate things, not all Keywords have 3 dates worth of data, some have only 2 for instance.

The simpler the SQL the better since my database is proprietary and I’m not quite sure what formulas are available, although I know it can do OVER(PARTITION BY) if that helps. Thank you!

UPDATE: I define the slope as best fit y=mx+p aka in excel it would be =slope()

Here is another actual example that I usually manipulate in excel:

Advertisement

Answer

The cleanest one I could make:

It uses Simple Linear Regression to calculate the slope.

Result:

Every database system seems to have a different approach to converting dates to numbers:

  • MySQL: TO_SECONDS(date) or TO_DAYS(date)
  • Oracle: TO_NUMBER(TO_CHAR(date, 'J')) or date - TO_DATE('1','yyyy')
  • MS SQL Server: CAST(date AS float) (or equivalent CONVERT)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement