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 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

按 YEAR( Date) 分组似乎并没有产生预期的差异。我已经尝试了我能想到的一切,但即使你按月或按年分组等,它似乎仍然会返回每日变化率。我认为我没有正确使用窗口,但我似乎无法弄清楚. 如果有人知道一本关于这种查询的好书,我也会很感激。谢谢。sqlfiddle 示例


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

我仍然不确定我是否理解为什么会这样,但它确实给了我想要的东西。使用另一个select语句作为 afrom似乎是这里的关键;如果没有 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
4

1 回答 1

1

尝试这个:

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
于 2013-11-11T16:58:43.793 回答