mysql获取当前计数直到结果

brccelvz  于 2021-06-21  发布在  Mysql
关注(0)|答案(5)|浏览(405)

这是我的数据集:

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 .

khbbv19g

khbbv19g1#

尝试此查询:

select @user_id_lag := 0;
select id, user_id, amount, added, status from (
    select case when @user_id_lag = user_id then 'recurring' else 'new' end status,
           @user_id_lag := user_id user_id,
           id, amount, added
    from tbl
    order by user_id, added
) a order by added

演示

rm5edbpk

rm5edbpk2#

请尝试以下操作:http://sqlfiddle.com/#!2011年9月6日

select *, case when num=1 then 'New' when num=2 then 'Recurring' end as status from 
(SELECT id,
    @row_number:=CASE
        WHEN @customer_no = userid THEN @row_number + 1
        ELSE 1
    END AS num,
    @customer_no:=userid as CustomerNumber

FROM
    test, (SELECT @customer_no:=0,@row_number:=0) as t
ORDER BY userid)a
yi0zb3m4

yi0zb3m43#

您想知道记录的日期是否是用户的最短日期:

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() .

llew8vvj

llew8vvj4#

你可以简单地 JOIN 使用分组数据:

SELECT
    userdata.*,
    CASE WHEN userdata.added = groupsq.first_date THEN 'new' ELSE 'recurring' END AS status
FROM userdata
INNER JOIN (
    SELECT user_id, MIN(added) AS first_date
    FROM userdata
    GROUP BY user_id
) AS groupsq ON userdata.user_id = groupsq.user_id
u7up0aaq

u7up0aaq5#

SELECT id,user_id , amount , added    , 'new' AS status FROM new_table GROUP BY user_id
UNION ALL 
SELECT id, user_id , amount , added    , 'recursive' AS status FROM new_table 
WHERE id  NOT IN (SELECt * FROM ( SELECT idnew_table FROM   new_table GROUP BY user_id ) AS t )

相关问题