在SQL中获取子查询的结果

时间:2014-07-23 13:13:27

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

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

Tables:
- Invoices
- Customers

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

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

2 个答案:

答案 0 :(得分:2)

您想使用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

答案 1 :(得分: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;