在Postgresql
中,有效地选择了每个组的第一行 >本指南演示了如何在PostgreSQL中有效检索每个组的最早条目,这是使用分组数据时的常见任务。 最有效的方法利用
子句。
DISTINCT ON
子句DISTINCT ON
> PostgreSQL的
DISTINCT ON
<code class="language-sql">SELECT DISTINCT ON (column_list) FROM table_name ORDER BY column_list, ...;</code>
考虑带有列,和
如果列允许null值,则在>子句中include
>子征服: ,然后为这些客户的最小 临时表/ctes:purchases
id
customer
重要的考虑因素:total
id
<code class="language-sql">SELECT DISTINCT ON (customer)
id, customer, total
FROM purchases
ORDER BY customer, total DESC, id;</code>
对于每个客户的数据集,替代策略可能会更有效:total
>或NULLS LAST
中的列。
ORDER BY
SELECT
> DISTINCT ON
以不同于分组顺序的最终结果,嵌套查询并应用辅助ORDER BY
子句。
DISTINCT ON
>
ORDER BY
(customer, total DESC, id)
选择该行。
以上是如何检索 PostgreSQL 中每个组的最早条目?的详细内容。更多信息请关注PHP中文网其他相关文章!