结果集取决于列值更改(先前日期)

时间:2018-05-10 11:41:05

标签: sql sqlite

我有一个带有名称指示符的表和四列每月存储数据的列。现在我想分析数据。首先,我比较了一年(13个月)的一些值,我发现我甚至需要对列的最后一次值更改来决定应该采取哪种结果(这使事情变得如此复杂)。

这里是一年的SQL命令和结果集的一部分:

SELECT e.* FROM indicators AS e ORDER BY e.date DESC LIMIT 13

date            interest_rate inflation_rate exchange_rate
"2018-04-02"    0.0           1.1            1.2321
[...]
"2017-04-03"    0.0           2.0            1.0691

当我发现intrest_rate列没有结果集中的最后一个更改值时,问题出现了。在查看stackoverflow之后,我进入了另一个SQL命令:

SELECT c.* FROM indicators AS c WHERE (c.date >= 
    ( SELECT b.date FROM indicators AS b WHERE b.interest_rate <>
        ( SELECT a.interest_rate FROM indicators AS a WHERE b.date < a.date ORDER BY a.date DESC LIMIT 1 ) 
      ORDER BY b.date DESC  LIMIT 1 ) 
    )

date            interest_rate inflation_rate exchange_rate
"2016-03-01"    0.05          0.3            1.0888
"2016-04-01"    0.0          -0.2            1.1385
[...]
"2017-04-03"    0.0           2.0            1.0691

问题是有两个查询应该找到正确的日期。目前日期是2016年3月1日。

用min(),max(),LEFT JOIN等播放arround后,我找到了UNION的解决方案。

SELECT result1.* FROM 
( SELECT c.* FROM indicators AS c WHERE (c.date >= 
    ( SELECT b.date FROM indicators AS b WHERE b.interest_rate <>
        ( SELECT a.interest_rate FROM indicators AS a WHERE b.date < a.date ORDER BY a.date DESC LIMIT 1 ) 
      ORDER BY b.date DESC LIMIT 1 ) 
    ) 
) AS result1
UNION 
SELECT result2.* FROM ( SELECT e.* FROM indicators AS e ORDER BY e.date DESC LIMIT 13) AS result2

如果我认为如果费率变化超过13个月,此解决方案将起作用。如果interest_rate更改在13个月内,结果是否正确?我可能有一个更简单的解决方案吗?

编辑:有点系统。 如果通货膨胀率低于一年的通货膨胀率 - 一点 如果汇率低于一年的汇率 - 一点。 最后一次利率下降了 - 一点。

这是直到第一次利率变化的完整结果:

date            intr_r  infl_r  exchange_rate
"2016-03-01"    "0.05"  "0.3"   "1.0888"
"2016-04-01"    "0.0"   "-0.2"  "1.1385"
"2016-05-02"    "0.0"   "0.0"   "1.1403"
"2016-06-01"    "0.0"   "-0.2"  "1.1154"
"2016-07-01"    "0.0"   "-0.1"  "1.1102"
"2016-08-01"    "0.0"   "0.1"   "1.1113"
"2016-09-01"    "0.0"   "0.2"   "1.1132"
"2016-10-04"    "0.0"   "0.2"   "1.1161"
"2016-11-01"    "0.0"   "0.4"   "1.0946"
"2016-12-01"    "0.0"   "0.5"   "1.0635"
"2017-01-02"    "0.0"   "0.6"   "1.0541"
"2017-02-01"    "0.0"   "1.1"   "1.0755"
"2017-03-01"    "0.0"   "1.8"   "1.0597"
"2017-04-03"    "0.0"   "2.0"   "1.0691"
"2017-05-02"    "0.0"   "1.5"   "1.093"
"2017-06-01"    "0.0"   "1.9"   "1.1221"
"2017-07-03"    "0.0"   "1.4"   "1.1412"
"2017-08-01"    "0.0"   "1.3"   "1.1727"
"2017-09-01"    "0.0"   "1.3"   "1.1825"
"2017-10-02"    "0.0"   "1.5"   "1.1806"
"2017-11-01"    "0.0"   "1.5"   "1.1638"
"2017-12-01"    "0.0"   "1.4"   "1.1849"
"2018-01-02"    "0.0"   "1.5"   "1.1993"
"2018-02-01"    "0.0"   "1.4"   "1.2457"
"2018-03-01"    "0.0"   "1.3"   "1.2214"
"2018-04-02"    "0.0"   "1.1"   "1.2321"

我想计算积分作为投资的指标。

0 个答案:

没有答案