通过匹配两个表中的符号来计算价格变化,并按设定的间隔计算价格差

时间:2019-05-19 00:32:29

标签: mysql

  

我有两个表,如下所示。两个表都有符号列。   assetList表具有lastPriceUSD和VWAPUSD表具有vwapUSD   带有createdAt列。

     

VWAPUSD表每10分钟更新一次,每个商店的存储价格   资产。我想匹配两个表中的符号,然后计算   24h / 7d / 30d间隔的价格差异。

资产列表表

+----+--------------+--------+-----------------+------------------------+
| id | name         | symbol | lastPriceUSD    | circulatingSupply      |
+----+--------------+--------+-----------------+------------------------+
|  1 | Bitcoin      | BTC    | 7293.2028511419 |    17688625.0000000000 |
|  2 | Ethereum     | ETH    |  234.9522240344 |   105978867.0616000000 |
|  3 | XRP          | XRP    |    0.3711016204 | 42004966728.0000000000 |
|  4 | Bitcoin Cash | BCHABC |  359.6217859183 |    17770489.6469232500 |
|  5 | Litecoin     | LTC    |   86.7230191550 |    61699595.7334713500 |
+----+--------------+--------+-----------------+------------------------+

VWAPUSD表

+--------+--------+----------------+---------------------+
| vwapId | symbol | vwapUSD        | createdAt           |
+--------+--------+----------------+---------------------+
|      2 | ETH    | 184.2507663730 | 2019-05-12 23:36:11 |
|      3 | LTC    |  84.8173610151 | 2019-05-12 23:36:11 |
|      4 | BNB    |  20.5221663735 | 2019-05-12 23:36:11 |
|      5 | NEO    |   9.1588715813 | 2019-05-12 23:36:11 |
|      6 | QTUM   |   2.3849431039 | 2019-05-12 23:36:11 |
+--------+--------+----------------+---------------------+
  

这就是我正在尝试的

SELECT al.symbol,
       al.lastPriceUSD,
       al.circulatingSupply,
       vw.symbol,
       vw.vwapUSD,
       100 * (al.lastPriceUSD - vw.vwapUSD) / al.lastPriceUSD as difference
FROM assetList al JOIN VWAPUSD vw
ON al.symbol = vw.symbol
WHERE al.symbol = vw.symbol AND
      vw.createdAt >= NOW() - INTERVAL 1 DAY
ORDER BY (al.circulatingSupply * al.lastPriceUSD) DESC

1 个答案:

答案 0 :(得分:0)

使用标量子查询

SELECT al.symbol
     , al.lastPriceUSD
     , al.circulatingSupply
     , ( SELECT 100 * (al.lastPriceUSD - vw.vwapUSD) / al.lastPriceUSD
           FROM VWAPUSD vw
           WHERE vw.symbol = al.symbol
             AND vw.createdAt >= now() -interval 1 day 
             AND vw.createdAt <  now() -interval 1 day + interval 10 minute
       ) diff24h
     , ( SELECT 100 * (al.lastPriceUSD - vw.vwapUSD) / al.lastPriceUSD
           FROM VWAPUSD vw
           WHERE vw.symbol = al.symbol
             AND vw.createdAt >= now() -interval 7 day 
             AND vw.createdAt <  now() -interval 7 day + interval 10 minute
       ) diff7d  
  FROM assetList al 
  ORDER BY (al.circulatingSupply * al.lastPriceUSD) DESC