How to calculate the slope in SQL

前端 未结 4 1183
一整个雨季
一整个雨季 2020-12-28 18:41

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

Date        |  Keyword  |  Score    
2012-01-10  |  ipad          


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-28 19:08

    If you're defining slope as just the slope from the earliest point to the latest point, and if score only increases with date, then you can get the output above with this:

    SELECT *
      FROM scores
      JOIN
        (SELECT foo.keyword,
                (MAX(score)-MIN(score)) / DATEDIFF(MAX(date),MIN(date)) AS score
         FROM scores
         GROUP BY keyword) a
      USING(keyword);
    

    However if you want linear regression, or if scores can decrease as well as increase with time, you'll need something more complex.

提交回复
热议问题