【问题标题】:Get the results of a subquery in SQL在 SQL 中获取子查询的结果
【发布时间】:2023-03-25 02:00:02
【问题描述】:

如何创建联接以获取所有客户的最新发票?

Tables:
- Invoices
- Customers

Customers table has: id, last_invoice_sent_at, last_invoice_guid
Invoices table has: id, customer_id, sent_at, guid

我想获取每位客户的最新发票,并使用该数据更新客户表中的 last_invoice_sent_at 和 last_invoice_guid。

【问题讨论】:

  • 放一些数据以供参考和预期输出

标签: sql postgresql sql-update greatest-n-per-group


【解决方案1】:

您想使用distinct on。对于由customer_id 和invoice 排序的查询,它将返回distinct on 中指示的每个不同值的第一行。也就是下面带有* 的行:

customer_id | sent_at     |
1           | 2014-07-12  | * 
1           | 2014-07-10  | 
1           | 2014-07-09  |
2           | 2014-07-11  | *
2           | 2014-07-10  |

所以您的更新查询可能如下所示:

update customers
set last_invoice_sent_at = sent_at
from (
  select distinct on (customer_id)
    customer_id,
    sent_at
  from invoices
  order by customer_id, sent_at desc
) sub
where sub.customer_id = customers.customer_id

【讨论】:

    【解决方案2】:

    @Konrad 提供了完美的 SQL 语句。但是由于我们只对单个列感兴趣,GROUP BY 将比DISTINCT ON 更高效(这对于从同一行检索多个列非常有用):

    UPDATE customers c
    SET    last_invoice_sent_at = sub.last_sent
    FROM  (
       SELECT customer_id, max(sent_at) AS last_sent
       FROM   invoices
       GROUP  BY 1
       ) sub
    WHERE sub.customer_id = c.customer_id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多