gpt4 book ai didi

postgresql - 选择按某些列排序但在另一列不同的行

转载 作者:行者123 更新时间:2023-11-29 11:09:13 25 4
gpt4 key购买 nike

与 - PostgreSQL DISTINCT ON with different ORDER BY 相关

我有表格购买(product_id、purchased_at、address_id)

示例数据:

| id | product_id |   purchased_at    | address_id |
| 1 | 2 | 20 Mar 2012 21:01 | 1 |
| 2 | 2 | 20 Mar 2012 21:33 | 1 |
| 3 | 2 | 20 Mar 2012 21:39 | 2 |
| 4 | 2 | 20 Mar 2012 21:48 | 2 |

我期望的结果是每个 address_id 的最近购买的产品(整行),并且该结果必须按 purchased_at 字段的后代顺序排序:

| id | product_id |   purchased_at    | address_id |
| 4 | 2 | 20 Mar 2012 21:48 | 2 |
| 2 | 2 | 20 Mar 2012 21:33 | 1 |

使用查询:

SELECT DISTINCT ON (address_id) purchases.address_id, purchases.*
FROM "purchases"
WHERE "purchases"."product_id" = 2
ORDER BY purchases.address_id ASC, purchases.purchased_at DESC

我得到:

| id | product_id |   purchased_at    | address_id |
| 2 | 2 | 20 Mar 2012 21:33 | 1 |
| 4 | 2 | 20 Mar 2012 21:48 | 2 |

所以行是一样的,但是顺序错了。有什么办法可以解决吗?

最佳答案

非常明确的问题:)

SELECT t1.* FROM purchases t1
LEFT JOIN purchases t2
ON t1.address_id = t2.address_id AND t1.purchased_at < t2.purchased_at
WHERE t2.purchased_at IS NULL
ORDER BY t1.purchased_at DESC

而且很可能是一种更快的方法:

SELECT t1.* FROM purchases t1
JOIN (
SELECT address_id, max(purchased_at) max_purchased_at
FROM purchases
GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC

关于postgresql - 选择按某些列排序但在另一列不同的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9796078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com