[英]How to use SQL find first matching result from one table in another table?
Suppose I had two tables:假设我有两张桌子:
Customer -
ID | Name | Etc
1 | One |
2 | Two |
3 | Three |
4 | Four |
5 | Five |
... | ... |
Sales -
Customer ID | Date | Amount
5 | 1/20 | $45
5 | 3/19 | $145
3 | 8/19 | $453
7 | 3/20 | $4513
3 | 9/20 | ...
1 | 3/20 | ...
1 | 1/20 | ...
What I want to do is write a query that will find the first sale for each customer.我想做的是编写一个查询,为每个客户找到第一笔销售。 I am not sure exactly how to do it.
我不确定该怎么做。 I feel like this is group by problem, but the answer is not coming to me.
我觉得这是按问题分组的,但答案并没有出现。
EDIT: I feel like my first data table did not fully explain my problem.编辑:我觉得我的第一个数据表并没有完全解释我的问题。 (Honestly, I didn't even realize this facet of my problem until, I was coding the solution) Note: There is more than one customer per sale.
(老实说,在我编写解决方案之前,我什至没有意识到我的问题的这一方面) 注意:每次销售有多个客户。
Sales -
Sale ID | Customer ID | Date | Amount
1 | 5 | 1/20 | $45
5 | 5 | 3/19 | $145
8 | 3 | 8/19 | $453
7 | 7 | 3/20 | $4513
3 | 4 | 9/20 | ...
2 | 1 | 3/20 | ...
1 | 1 | 1/20 | ...
You can use a subquery which assigns a row number to each sale for each customer, ordering by ascending date, and then select only the first rows:您可以使用子查询为每个客户的每次销售分配一个行号,按日期升序排序,然后 select 仅第一行:
SELECT "Customer ID", "Date", "Amount"
FROM (
SELECT "Customer ID", "Date", "Amount",
ROW_NUMBER() OVER (PARTITION BY "Customer ID" ORDER BY "Date") AS rn
FROM Sales) s
WHERE rn = 1
Nick's solution is probably the most performant, but if you wanted to use GROUP BY
here, you could do that: Nick 的解决方案可能是性能最高的,但如果你想在这里使用
GROUP BY
,你可以这样做:
SELECT
c.ID,
c.Name,
s1.Date,
s1.Amount
FROM Customer c
INNER JOIN Sales s1 ON c.ID = s1."Customer ID"
INNER JOIN
(
SELECT "Customer ID", MIN(Date) AS FirstSaleDate
FROM Sales
GROUP BY "Customer ID"
) s2
ON s1."Customer ID" = s2."Customer ID" AND
s1.Date = s2.FirstSaleDate
ORDER BY
c.ID,
c.Name;
In Oracle, you can use keep
:在 Oracle 中,您可以使用
keep
:
select customer_id, min(date) as first_sales_date,
max(amount) keep (dense_rank first order by date asc) as first_amount
from sales
group by customer_id;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.