尝试根据客户在 SQL 上的购买频率查找客户数量并添加客户的销售额
Posted
技术标签:
【中文标题】尝试根据客户在 SQL 上的购买频率查找客户数量并添加客户的销售额【英文标题】:Trying to find the count of customers and add the sales of the customer in based on their purchase frequency on SQL 【发布时间】:2020-02-21 21:57:22 【问题描述】:我正在尝试根据客户在 2019 年的购买次数来查找客户数量和销售额
txn_date Customer_ID Transaction_Number Sales Reference(not in the SQL table)
1/2/2019 1 12345 $10 First Purchase SLS
4/3/2019 1 65890 $20 Second Purchase SLS
3/22/2019 3 64453 $30 First Purchase SLS
4/3/2019 4 88567 $20 First Purchase SLS
1/23/2019 5 89464 $40 First Purchase SLS
4/3/2019 5 99674 $30 Second Purchase SLS
4/3/2019 6 32224 $20 First Purchase SLS
1/23/2019 6 46466 $30 Second Purchase SLS
我正在尝试得到以下结果:
Customer_Count Transaction_Count Sum(Sales)
1st Purchase 5 5 $120
2nd Purchase 3 3 $80
我尝试了以下查询:
SELECT COUNT(DISTINCT INDIVIDUAL_ID),
CASE WHEN COUNT_OF_TRANSACTIONS = 1 THEN '1'
WHEN COUNT_OF_TRANSACTIONS = 2 THEN '2'
WHEN COUNT_OF_TRANSACTIONS = 3 THEN '3'
WHEN COUNT_OF_TRANSACTIONS = 4 THEN '4'
WHEN COUNT_OF_TRANSACTIONS >= 5 THEN '5+' END AS TXN_TYPE,
SUM(DOLLAR_VALUE_US),
SUM( COUNT_OF_TRANSACTIONS)
FROM customerorder
GROUP BY CASE WHEN COUNT_OF_TRANSACTIONS = 1 THEN '1'
WHEN COUNT_OF_TRANSACTIONS = 2 THEN '2'
WHEN COUNT_OF_TRANSACTIONS = 3 THEN '3'
WHEN COUNT_OF_TRANSACTIONS = 4 THEN '4'
WHEN COUNT_OF_TRANSACTIONS >= 5 THEN '5+' END
ORDER BY 1 ASC;
我想查找客户数量及其销售额。因此,对于第一次购买,客户计数将是至少进行一次购买的任何人以及销售额。对于第二次购买,从技术上讲,它应该包括第一次购买的每个人,但只包括第二次交易的销售额。
【问题讨论】:
【参考方案1】:如果我理解正确,您想列举每个客户的订单,然后汇总:
select seqnum, count(*) as num_customers, sum(sales)
from (select co.*,
row_number() over (partition by customer_id order by txn_date) as seqnum
from customerorder co
) co
group by seqnum
order by seqnum;
【讨论】:
我想知道客户的数量和他们的销售额。因此,对于第一次购买,客户计数将是至少进行一次购买的任何人以及销售额。对于第二次购买,从技术上讲,它应该包括第一次购买的每个人,但只包括第二次交易的销售额。 我认为我一起提出的查询是按客户的交易数量对客户进行分类。我认为这是不正确的。 @Somya 。 . .这个查询应该做你想做的事。以上是关于尝试根据客户在 SQL 上的购买频率查找客户数量并添加客户的销售额的主要内容,如果未能解决你的问题,请参考以下文章