为每位客户选择首次购买

时间:2013-11-06 01:53:37

标签: sql sql-server sql-server-2005

我们正尝试在与此类似的表格中为每位客户选择首次购买:

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 个答案:

答案 0 :(得分:5)

您可以简单地将您提出的查询视为内部查询。这也适用于旧版本的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

答案 1 :(得分:2)

SELECT 
    transaction_no,
    customer_id,
    operator_id,
    purchase_date
FROM
(SELECT 
    *,
    ROW_NUMBER () OVER ( [ PARTITION BY customer_id order by purchase_date ) "occurence"
    FROM Sales_Transactions_Header
)
WHERE occurence = 1

答案 2 :(得分:1)

听起来像是CTE的工作!

Clicky!

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

答案 3 :(得分:0)

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

select * from customer_sale_details 
     where purchase_date in (select min(purchase_date)
           from customer_sale_details c1 group by c1.customer_id);