我正在尝试重写不使用相关查询的SQL查询。 这是查询:
SELECT DISTINCT v.vendor_name, i.invoice_number, i.invoice_date, i.invoice_total
FROM vendors v JOIN invoices i
ON i.vendor_id = v.vendor_id
AND i.invoice_date = (SELECT MIN(invoice_date)
FROM invoices
WHERE vendor_id = v.vendor_id)
我尝试了很多方法,但我总是遇到这个问题: 我不知道如何在此结果集中集成invoice_number和invoice_total列。
SELECT vendor_name, MIN(invoice_date)
FROM vendors JOIN invoices USING (vendor_id)
GROUP BY vendor_name
有人可以帮助我吗?
答案 0 :(得分:1)
一种方法是使用分析函数rank
SELECT DISTINCT vendor_name, invoice_number, invoice_date, invoice_total
FROM (SELECT v.vendor_name,
i.invoice_number,
i.invoice_date,
i.invoice_total,
rank() over (partition by v.vendor_id
order by i.invoice_date asc) rnk
FROM vendors v
JOIN invoices i
ON i.vendor_id = v.vendor_id)
WHERE rnk = 1
如果您希望提高查询的效果,我强烈质疑您是否需要DISTINCT
,因为这会强制进行额外排序。通常,当开发人员真正错过某些连接条件时,会使用DISTINCT
来正确消除重复的行。