11

我们正在尝试在类似于此的表中为每个客户选择第一次购买:

transaction_no  customer_id  operator_id  purchase_date
20503           1            5            2012-08-24
20504           1            7            2013-10-15
20505           2            5            2013-09-05
20506           3            7            2010-09-06
20507           3            7            2012-07-30

我们试图实现的查询的预期结果是:

transaction_no  customer_id  operator_id  first_occurence
20503           1            5            2012-08-24
20505           2            5            2013-09-05
20506           3            7            2010-09-06

我们得到的最接近的是以下查询:

SELECT customer_id, MIN(purchase_date) As first_occurence
FROM Sales_Transactions_Header
GROUP BY customer_id;

结果如下:

customer_id  first_occurence
1            2012-08-24
2            2013-09-05
3            2010-09-06

但是,当我们选择其余所需字段时,我们显然必须将它们添加到 GROUP BY 子句中,这将使 MIN 的结果不同。我们也尝试过自己加入它,但没有取得任何进展。

我们如何在不混淆聚合函数的情况下获得其余的相关值?

4

4 回答 4

11

您可以简单地将您提出的查询视为内部查询。这也适用于旧版本的 SQL Server(您没有指定 SQL Server 的版本)。

SELECT H.transaction_no, H.customer_id, H.operator_id, H.purchase_date
FROM Sales_Transactions_Header H
INNER JOIN
    (SELECT customer_id, MIN(purchase_date) As first_occurence
    FROM Sales_Transactions_Header
    GROUP BY customer_id) X
ON H.customer_id = X.customer_id AND H.purchase_date = X.first_occurence
于 2013-11-06T02:04:25.940 回答
7

您可以使用ROW_NUMBER函数来帮助您。

这是为您的情况执行此操作的方法。

WITH Occurences AS 
(
    SELECT 
        *,
        ROW_NUMBER () OVER (PARTITION BY customer_id order by purchase_date ) AS "Occurence"            
    FROM Sales_Transactions_Header
)
SELECT 
    transaction_no,
    customer_id,
    operator_id,
    purchase_date
FROM Occurences 
WHERE Occurence = 1
于 2013-11-06T02:05:33.807 回答
3

听起来像是 CTE 的工作!

咔哒!

CTE 将允许您获得每个客户的最早购买日期。然后,您将其加入到您在 customer_id 和日期上的原始表中,获取该交易的其余信息。

像这样:

with first_date as(
  select customer_id,
  min(purchase_date) as first_purchase
  from
  table1
  group by
  customer_id
)
select
t1.transaction_no,
t1.customer_id,
t1.operator_id,
t1.purchase_date
from
table1 t1
inner join first_date
on
purchase_date = first_purchase
and t1.customer_id = first_date.customer_id
于 2013-11-06T02:03:32.590 回答
0

下面的查询也将提供解决方案

select * from customer_sale_details 
     where purchase_date in (select min(purchase_date)
           from customer_sale_details c1 group by c1.customer_id); 
于 2020-08-08T10:38:59.933 回答