PostgreSQL:选择列并从组中排除

标签 postgresql

这个问题可能以不同的形式被问过,但我找不到答案。

我有表订单

date, quantity_ordered, unit_cost_cents, product_model_number, title

我愿意:

SELECT 
  model_number,
  title,
  SUM(unit_cost_cents  / 100.00 * quantity_ordered) as total
FROM orders
GROUP BY model_number
HAVING SUM(quantity_submitted) > 0
ORDER BY total DESC

但它也需要按 title 分组。

我的问题是我的 title 随着时间的推移而改变。我想保留标题并简单地显示/选择最新的 title 而不是按标题分组,这会使数字不同。

最佳答案

您可以使用子查询来获取最新的标题:

SELECT 
  model_number,
  (select max(title) from orders where date = (
    select max(date) from orders where model_number = o.model_number)
  ) title,
  SUM(unit_cost_cents  / 100.00 * quantity_ordered) as total
FROM orders o
GROUP BY model_number 
HAVING SUM(quantity_submitted) > 0
ORDER BY total DESC

我使用 select max(title) 而不是 select title 来确保子查询不会返回超过 1 行(以防万一)。

关于PostgreSQL:选择列并从组中排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56262300/

相关文章:

django - 如何使用 postgres 在 django 中设置对重音不敏感的过滤器?

performance - PostgreSQL 的写入速度为何比 SQLite 快得多?

sql - 子查询中的多个 json_object_agg 函数返回语法错误

sql - 如何仅从 postgres json 中选择特定键

postgresql - Postgres Slony-I问题

android - 通过 JDBC 连接到 PostgreSQL - NetworkOnMainThreadException

postgresql - postgresql中带有临时表的存储函数

apache - 使用 PostgreSQL 解析 apache 日志

sql - PostgreSQL 在选择查询中重用计算结果

postgresql - WITH 语句中的查询是否在 PostgreSQL 的单个事务中执行?