如何按日期返回每个字段的最新行
Posted
技术标签:
【中文标题】如何按日期返回每个字段的最新行【英文标题】:How to return latest rows by date for each field 【发布时间】:2019-09-08 16:20:41 【问题描述】:我在 postgres 9.4 上。我想查询我的adjustments
表以获取每个字段的最新调整。一些adjustments
可以调整多个字段。
示例 1
+---------------+-------------+----------------+---------------+
| available_qty | on_hand_qty | backstock_qty | date |
+---------------+-------------+----------------+---------------+
| null | 2 | null | 2018-01-03 |
| 1 | null | 10 | 2018-01-04 |
| null | null | 2 | 2018-01-01 |
| 3 | 3 | null | 2018-01-02 |
+---------------+-------------+----------------+---------------+
...查询每个字段的最新调整将导致:
+---------------+-------------+----------------+---------------+
| available_qty | on_hand_qty | backstock_qty | date |
+---------------+-------------+----------------+---------------+
| null | 2 | null | 2018-01-03 |
| 1 | null | 10 | 2018-01-04 |
+---------------+-------------+----------------+---------------+
示例 2
+---------------+-------------+----------------+---------------+
| available_qty | on_hand_qty | backstock_qty | date |
+---------------+-------------+----------------+---------------+
| null | 2 | null | 2018-01-03 |
| 1 | null | null | 2018-01-04 |
| null | null | 2 | 2018-01-01 |
| null | null | 3 | 2018-01-02 |
| 3 | null | null | 2018-01-02 |
| null | 4 | null | 2018-01-01 |
+---------------+-------------+----------------+---------------+
...查询每个字段的最新调整将导致:
+---------------+-------------+----------------+---------------+
| available_qty | on_hand_qty | backstock_qty | date |
+---------------+-------------+----------------+---------------+
| null | 2 | null | 2018-01-03 |
| 1 | null | null | 2018-01-04 |
| null | null | 3 | 2018-01-02 |
+---------------+-------------+----------------+---------------+
我可以通过大量UNION
查询来实现这一点:
(SELECT * FROM adjustments WHERE available_qty IS NOT NULL ORDER BY date DESC LIMIT 1)
UNION
(SELECT * FROM adjustments WHERE on_hand_qty IS NOT NULL ORDER BY date DESC LIMIT 1)
UNION
(SELECT * FROM adjustments WHERE backstock_qty IS NOT NULL ORDER BY date DESC LIMIT 1)
...但是这可以通过一个查询来实现吗?实际上,这里可以有很多领域。提前致谢!
【问题讨论】:
试试这个:***.com/a/20748872/11610186,在你的情况下:sqlfiddle.com/#!17/f1a44/5 @GrzegorzSkibinski 谢谢,快到了!有没有办法同时返回每个对应字段的日期值? 理想情况下,我希望返回实际的adjustments
行
我把整个事情放在下面的答案中。
【参考方案1】:
好的,这就是您要查找的内容: (顺序是 - 字段,然后是最近调整的日期)
select
first_value(available_qty) over (order by available_qty is null, date desc),
first_value(date) over (order by available_qty is null, date desc),
first_value(on_hand_qty) over (order by on_hand_qty is null, date desc),
first_value(date) over (order by on_hand_qty is null, date desc),
first_value(backstock_qty) over (order by backstock_qty is null, date desc),
first_value(date) over (order by backstock_qty is null, date desc)
from
adjustment
limit 1
并更新SQL fiddle
【讨论】:
以上是关于如何按日期返回每个字段的最新行的主要内容,如果未能解决你的问题,请参考以下文章