Reputation: 65
This is my data set:
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
What I need is a query to produce the following result:
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
I want to get status of user id either previous it occurred or not. If not than show new
else recurring
.
Upvotes: 0
Views: 70
Reputation: 3
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 )
Upvotes: 0
Reputation: 272386
You can simply JOIN
with grouped data:
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
Upvotes: 0
Reputation: 37483
Try below: http://sqlfiddle.com/#!9/6ef4c6/11
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
Upvotes: 1
Reputation: 37500
Try this query:
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
Upvotes: 1
Reputation: 95090
You want to know whether a record's date is the minimum date for the user:
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;
The same can of course be done by joining the subquery instead or by using a correlated EXISTS
clause. And as of MySQL 8.0 I'd use MIN() OVER()
.
Upvotes: 1