每周获取每个客户的最新记录
Grabbing most recent record per customer per week
我正在尝试查询 table 和 return 按周分组的客户选择的最新组合。例如,这里是 table:
(int) (string) (int) (bigint)
Customer ID Choice Week Inserted at
100 a, b, c 2 20171002
100 a, b 2 20171004
101 b, c, d 2 20171002
102 a, c, d 2 20171002
103 a, b, c 2 20171002
103 a, b, d 2 20171003
100 a, b, c, d 3 20171010
101 a, c, d 3 20171010
101 b, c, d 3 20171011
102 a, b 3 20171010
103 a, b, c 3 20171010
103 b, c, d 3 20171012
103 a, b, d 3 20171014
这是我要生成的查询:
Customer ID Choice Week Inserted at
100 a, b 2 20171004
101 b, c, d 2 20171002
102 a, c, d 2 20171002
103 a, b, d 2 20171003
100 a, b, c, d 3 20171010
101 b, c, d 3 20171011
102 a, b 3 20171010
103 a, b, d 3 20171014
一个客户一天只能修改一次他们的选择,所以我不用担心一个客户一天修改很多。
这就是我的开始,但缺少很多行。有什么反馈吗?
SELECT c.customer, c.combo, c.week, c.date
FROM tableCombos AS c
WHERE not exists (SELECT *
FROM tableCombos AS recent
WHERE recent.customer = c.customer
AND recent.date > c.date)
使用window函数:
select tc.*
from (select tc.*,
row_number() over (partition by customer, week order by date desc) as seqnum
from tableCombos tc
) tc
where seqnum = 1;
首先我想获取按周和客户分组的最大日期:
select customerId , week, max(insertedAt) as date
group by customerId , WEEK
之后,我可以将此数据集与主要 table
SELECT c.customer, c.combo, c.week, c.date
FROM tableCombos AS c
join (select customerId , week, max(insertedAt) as date
group by customerId , WEEK) X
on c.customerId = X.customerId
and c.week = X.week
and c.date = X.date
我正在尝试查询 table 和 return 按周分组的客户选择的最新组合。例如,这里是 table:
(int) (string) (int) (bigint)
Customer ID Choice Week Inserted at
100 a, b, c 2 20171002
100 a, b 2 20171004
101 b, c, d 2 20171002
102 a, c, d 2 20171002
103 a, b, c 2 20171002
103 a, b, d 2 20171003
100 a, b, c, d 3 20171010
101 a, c, d 3 20171010
101 b, c, d 3 20171011
102 a, b 3 20171010
103 a, b, c 3 20171010
103 b, c, d 3 20171012
103 a, b, d 3 20171014
这是我要生成的查询:
Customer ID Choice Week Inserted at
100 a, b 2 20171004
101 b, c, d 2 20171002
102 a, c, d 2 20171002
103 a, b, d 2 20171003
100 a, b, c, d 3 20171010
101 b, c, d 3 20171011
102 a, b 3 20171010
103 a, b, d 3 20171014
一个客户一天只能修改一次他们的选择,所以我不用担心一个客户一天修改很多。
这就是我的开始,但缺少很多行。有什么反馈吗?
SELECT c.customer, c.combo, c.week, c.date
FROM tableCombos AS c
WHERE not exists (SELECT *
FROM tableCombos AS recent
WHERE recent.customer = c.customer
AND recent.date > c.date)
使用window函数:
select tc.*
from (select tc.*,
row_number() over (partition by customer, week order by date desc) as seqnum
from tableCombos tc
) tc
where seqnum = 1;
首先我想获取按周和客户分组的最大日期:
select customerId , week, max(insertedAt) as date
group by customerId , WEEK
之后,我可以将此数据集与主要 table
SELECT c.customer, c.combo, c.week, c.date
FROM tableCombos AS c
join (select customerId , week, max(insertedAt) as date
group by customerId , WEEK) X
on c.customerId = X.customerId
and c.week = X.week
and c.date = X.date