获取最后可用的条目

时间:2019-09-23 16:27:19

标签: sql mariadb groupwise-maximum

我正在使用10.1.39-MariaDB - mariadb.org binary,并且具有下表:

| id    | date                | ticker | close     | createdAt           | updatedAt           | CompanyId |
|-------|---------------------|--------|-----------|---------------------|---------------------|-----------|
| 39869 | 2019-09-18 00:00:00 | AAPL   | 221.96160 | 2019-09-18 19:25:30 | 2019-09-18 19:25:30 | 238       |
| 39870 | 2019-09-17 00:00:00 | AAPL   | 220.70000 | 2019-09-18 19:25:30 | 2019-09-18 19:25:30 | 238       |
| 39871 | 2019-09-16 00:00:00 | AAPL   | 219.90000 | 2019-09-18 19:25:30 | 2019-09-18 19:25:30 | 238       |
| 39872 | 2019-09-13 00:00:00 | AAPL   | 218.75000 | 2019-09-18 19:25:30 | 2019-09-18 19:25:30 | 238       |
| 39873 | 2019-09-12 00:00:00 | AAPL   | 223.09000 | 2019-09-18 19:25:30 | 2019-09-18 19:25:30 | 238       |

此外,我有以下查询以获取最后一天的前5名daily_returns

SELECT *
FROM (SELECT prices.*,
             CAST((`close` - @old_close) / @old_close AS DECIMAL(20, 10)) AS daily_return,
             @old_close := `close`
      FROM prices,
           (SELECT @old_close := 0 AS) AS t
      ORDER BY ticker,
              `date` ASC) AS tt
WHERE DATE >= DATE(NOW()) - INTERVAL 1 DAY
ORDER BY `date` DESC,
         daily_return DESC
LIMIT 5

但是,由于市场停滞,星期一我没有得到任何价格输入数据库,因此周一我只能得到空结果。

如何克服这个周末的问题,并采用数据库中发布的最后价格?

1 个答案:

答案 0 :(得分:1)

1个方法正在使用CASE语句-

SELECT *
FROM (SELECT prices.*,
             CAST((`close` - @old_close) / @old_close AS DECIMAL(20, 10)) AS daily_return,
             @old_close := `close`
      FROM prices,
           (SELECT @old_close := 0 AS) AS t
      ORDER BY ticker,
              `date` ASC) AS tt
WHERE DATE >= CASE WHEN DAYNAME(NOW()) = 'Monday' THEN DATE(NOW()) - INTERVAL 3 DAY  -- OR 2 DAY, DEPENDS UPON YOUR REQUIREMENT
                   ELSE DATE(NOW()) - INTERVAL 1 DAY END
ORDER BY `date` DESC,
         daily_return DESC
LIMIT 5