sql计算变化和年份的百分比

时间:2013-11-11 16:23:50

标签: mysql sql

我有一个模拟交易账户回报率的数据集。每天都有一个条目显示余额和未平仓权益。我想计算每年,每季度或每月的变化和百分比的收益或损失。我有这个工作日常数据,但由于某种原因,我似乎无法让它为年度数据工作。 每日数据的代码如下:

SELECT b.`Date`, b.Open_Equity, delta, 
       concat(round(delta_p*100,4),'%') as delta_p 
FROM  (SELECT *,
          (Open_Equity - @pequity) as delta,
          (Open_Equity - @pequity)/@pequity as delta_p,
          (@pequity:= Open_Equity)
       FROM tim_account_history p
          CROSS JOIN
            (SELECT @pequity:= NULL
             FROM tim_account_history
             ORDER by `Date` LIMIT 1) as a
       ORDER BY `Date`) as b
ORDER by `Date` ASC

按年份分组(Date)似乎没有产生预期的差异。我已经尝试了所有我能想到的东西,但即使你按月或按年分组,它似乎仍然会恢复每日变化率。我认为我没有正确使用窗口,但我似乎无法弄明白。如果有人知道关于这种查询的好书,我也会感激。 感谢。sqlfiddle example


使用Lolo贡献的内容,我添加了一些代码,因此数据来自一年的最后一天,而不是第一天。我也只需要Open_Equity,而不是总和。

我仍然不确定我理解为什么会这样,但它确实给了我正在寻找的东西。使用另一个select语句作为from似乎是关键所在;如果没有Lolo的帮助,我认为我不会想出这个。谢谢。

SELECT b.`yyyy`, b.Open_Equity, 
    concat('$',round(delta, 2)) as delta,
    concat(round(delta_p*100,4),'%') as delta_p 
FROM   (SELECT *,
          (Open_Equity - @pequity) as delta,
          (Open_Equity - @pequity)/@pequity as delta_p,
          (@pequity:= Open_Equity)
        FROM (SELECT (EXTRACT(YEAR FROM `Date`)) as `yyyy`, 
                (SUBSTRING_INDEX(GROUP_CONCAT(CAST(`Open_Equity` AS CHAR) ORDER BY `Date` DESC), ',', 1 )) AS `Open_Equity`
            FROM tim_account_history GROUP BY `yyyy` ORDER BY `yyyy` DESC) p
            CROSS JOIN
            (SELECT @pequity:= NULL) as a
       ORDER BY `yyyy` ) as b
ORDER by `yyyy` ASC

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT b.`Date`, b.Open_Equity, delta, 
       concat(round(delta_p*100,4),'%') as delta_p 
FROM  (SELECT *,
          (Open_Equity - @pequity) as delta,
          (Open_Equity - @pequity)/@pequity as delta_p,
          (@pequity:= Open_Equity)
       FROM (SELECT YEAR(`Date`) `Date`, SUM(Open_Equity) Open_Equity FROM tim_account_history GROUP BY YEAR(`Date`)) p
          CROSS JOIN
            (SELECT @pequity:= NULL) as a
       ORDER BY `Date` ) as b
ORDER by `Date` ASC