如何使用sql从一个表中的另一个表中查找第一个匹配结果?

w8f9ii69  于 2021-07-29  发布在  Java
关注(0)|答案(3)|浏览(380)

假设我有两张table:

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 | ...

我要做的是编写一个查询,它将查找每个客户的第一笔销售。我不知道该怎么做。我觉得这是一组问题,但我没有找到答案。
编辑:我觉得我的第一个数据表没有完全解释我的问题(老实说,我甚至没有意识到我的问题的这一方面,直到,我编码的解决方案)注意:有一个以上的客户每销售。

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 | ...
ffx8fchx

ffx8fchx1#

您可以使用子查询为每个客户的每个销售分配行号,按升序日期排序,然后仅选择第一行:

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

sqlfiddle演示

blpfk2vs

blpfk2vs2#

尼克的解决方案可能是最有效的,但如果你想使用 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;
vyswwuz2

vyswwuz23#

在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;

相关问题