这是我的数据集:
id user_id amount added
1 1 10.00 2018-09-11
2 2 10.00 2018-09-12
3 3 10.00 2018-09-13
4 1 8.00 2018-09-14
5 2 6.00 2018-09-15
我需要的是产生以下结果的查询:
id user_id amount added status
1 1 10.00 2018-09-11 new
2 2 10.00 2018-09-12 new
3 3 10.00 2018-09-13 new
4 1 8.00 2018-09-14 recurring
5 2 6.00 2018-09-15 recurring
我想获取用户 ID 之前发生与否的状态。如果不是,则显示 new
,否则 recurring
。
最佳答案
您想知道记录的日期是否是用户的最短日期:
select id, user_id, amount, added,
case when (user_id, added) in (select user_id, min(added) from mytable group by user_id)
then 'new' else 'recurring' as status
from mytable
order by id;
当然,同样可以通过加入子查询或使用相关的 EXISTS
子句来完成。从 MySQL 8.0 开始,我将使用 MIN() OVER()
。
关于Mysql获取当前计数直到结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52274513/