我想找到每个日期每个客户的最新购买记录(一个客户可能在给定日期进行了多次购买,而我想要该日期的最新购买记录)。我的数据框如下所示:
Customer_id | Date | Payment | Type
3 '2019-01-28 00:45:00' 128.93 Credit
2 '2019-01-26 01:00:00' 54.36 Debit
3 '2019-01-27 12:00:00' 93.99 Debit
3 '2019-01-28 03:15:00' 164.93 Credit
2 '2019-01-26 17:30:00' 56.74 Credit
2 '2019-01-28 19:15:00' 21.85 Credit
查询的输出应该给我类似以下内容(我按客户/日期组合返回一行,并按客户/日期订购。我不在乎类型-不论是贷方还是借方):< / p>
Customer_id | Date | Payment
2 '2019-01-26' 56.74
2 '2019-01-28' 21.85
3 '2019-01-27' 93.99
3 '2019-01-28' 164.93
到目前为止,这是我的代码:
SELECT
R1.Customer_id,
date_trunc('day', R1.Date),
R1.Payment
FROM Records R1
WHERE R1.Date = (SELECT MAX(R2.Date)
FROM Records R2
WHERE R2.Customer_id = R1.Customer_id)
GROUP BY Customer_id, date_trunc('day', R1.Date);
我给出的示例是我正在使用的数据的简化以及一些过滤条件,但应该可以捕捉到我所面临的主要问题。不确定是否正确,但是当我运行查询时,对于“分组依据”似乎不满意。我是sql的新手,很乐意提供帮助!
答案 0 :(得分:1)
此查询:
select Customer_id, Date::date, max(Date) maxdate from tablename group by customer_id, Date::date
获取每个客户的最新日期。
将其连接到主表以获取包含每个客户的最新日期的行:
select t.Customer_id, t.date, tt.Payment from (
select Customer_id, Date::date date, max(Date) maxdate from tablename group by customer_id, Date::date
) t inner join tablename tt
on tt.customer_id = t.customer_id and tt.date = t.maxdate
答案 1 :(得分:0)
在Postgres中,buildingCount++;
通常是最好的方法:
distinct on
尤其是,这可以利用select distinct on (customer_id, date::date) t.*
from t
order by customer_id, date desc;
上的索引。