我有一个包含客户的表,我想查找客户满足或超过一定数量的请求的月份。
该表具有customer_id每个请求的时间戳。
我要寻找的是客户满足或超过10000个请求的月份(或日期)。我已尝试将运行状况汇总到位,但这对我不起作用。如果有人知道我该怎么做,我将其保留在代码中。
我有以下内容:
SELECT
customer_id
, DATE_TRUNC(CAST(TIMESTAMP_MILLIS(created_timestamp) AS DATE), MONTH) as cMonth
, COUNT(created_timestamp) as searchCount
-- , SUM(COUNT (DISTINCT(created_timestamp))) OVER (ROWS UNBOUNDED PRECEDING) as RunningTotal2
FROM customer_requests.history.all
GROUP BY distributor_id, cMonth
ORDER BY 2 ASC, 1 DESC;
我所追求的代表是这样的。
customer requests cMonth totalRequests
cust1 6000 2017-10-01 6000
cust1 4001 2017-11-01 10001
cust2 4000 2017-10-01 4000
cust2 4000 2017-11-01 8000
cust2 4000 2017-12-01 12000
cust2 3000 2017-12-01 3000
cust2 3000 2017-12-01 6000
cust2 3000 2017-12-01 9000
cust2 3000 2017-12-01 12000
答案 0 :(得分:0)
假设使用SQL Server,请尝试以下操作(调整顶部的临界值以获取所需的交易数量;现在,它查找每个客户的千分之一交易)。
请注意,这不会返回未超过您的截止日期的客户,并假设每笔交易都有唯一的日期(或者如果有可能存在联系,则会发出连续的ID号以打破联系)。
DECLARE @cutoff INT = 1000;
WITH CTE
AS (SELECT customer_id,
transaction_ID,
transaction_date,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY transaction_date, transaction_ID) AS RN,
COUNT(transaction_ID) OVER (PARTITION BY customer_id) AS TotalTransactions
FROM #test)
SELECT DISTINCT
customer_id,
transaction_date as CutoffTransactionDate,
TotalTransactions
FROM CTE
WHERE RN = @cutoff;
工作原理:
row_number
按照进行交易的顺序为每个客户交易分配唯一的顺序标识符。 count
告诉您一个人进行的交易总数(再次假设每笔交易有一条记录-否则您将需要分别计算该记录,因为distinct
无法与partition
一起使用) 。
然后第二个select
返回每个客户及其日期的第1,000行(或您指定的行数),以及该客户的总数。
答案 1 :(得分:0)
答案 2 :(得分:0)
如果要累计,可以使用窗口函数。在标准SQL中,这看起来像:
SELECT customer_id,
DATE_TRUNC(CAST(TIMESTAMP_MILLIS(created_timestamp) AS DATE), MONTH) as cMonth
COUNT(*) as searchCount,
SUM(COUNT(*)) OVER (ORDER BY MIN(created_timestamp) as runningtotal
FROM customer_requests.history.all
GROUP BY distributor_id, cMonth
ORDER BY 2 ASC, 1 DESC;