计算百分比随时间的变化

时间:2014-03-06 16:38:09

标签: sql sql-server-2012

我已经创建了结构和示例数据here。我不确定如何计算随时间的变化。

我想要的结果集是:

a   | % growth
abc | 4.16
def | 0.83
hig | -0.2

%变化为(最后一个值 - 第一个值)/天:

a   | % growth
abc | (30-5) / 6
def | (6-1) / 6
hig | (4-5) / 5

我正在尝试:

SELECT a.*, 
       b.val, 
       c.val 
FROM   (SELECT a, 
               Min(dt) AS lowerDt, 
               Max(dt) AS upperDt 
        FROM   tt 
        GROUP  BY a) a 
       LEFT JOIN tt b 
              ON b.dt = a.lowerdt 
                 AND b.a = a.a 
       LEFT JOIN tt c 
              ON c.dt = a.upperdt 
                 AND b.a = a.a 

如果可能的话,我想避免CTE。

1 个答案:

答案 0 :(得分:2)

您不希望minmax,您真的需要firstlast

我这样做的一种方法是使用ROW_NUMBER()告诉我从开始或结束的位置。然后使用MAX(CASE WHEN pos=1 THEN x ELSE null END)获取我想要的值。

SELECT
  a,
  MAX(CASE WHEN pos_from_first = 1 THEN dt  ELSE NULL END)  AS first_date,
  MAX(CASE WHEN pos_from_final = 1 THEN dt  ELSE NULL END)  AS final_date,
  MAX(CASE WHEN pos_from_first = 1 THEN val ELSE NULL END)  AS first_value,
  MAX(CASE WHEN pos_from_final = 1 THEN val ELSE NULL END)  AS final_value,
  100
  *
  CAST(MAX(CASE WHEN pos_from_final = 1 THEN val ELSE NULL END) AS DECIMAL(9,6))
  /
  CAST(MAX(CASE WHEN pos_from_first = 1 THEN val ELSE NULL END) AS DECIMAL(9,6))
  -
  100                                                       AS perc_change
FROM
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY a ORDER BY dt  ASC) AS pos_from_first,
    ROW_NUMBER() OVER (PARTITION BY a ORDER BY dt DESC) AS pos_from_final,
    *
  FROM
    tt
)
  AS ordered
GROUP BY
  a

http://sqlfiddle.com/#!6/ad95d/11