这是我的数据集:
<div class="box">
<div class="image">
<a href="#"><img src="https://dummyimage.com/80x80/000/fff"></a>
<a href="#"><img src="https://dummyimage.com/80x80/000/fff"></a>
<a href="#"><img src="https://dummyimage.com/80x80/000/fff"></a>
<a href="#"><img src="https://dummyimage.com/80x80/000/fff"></a>
</div>
<div class="tools">
<a href="#">View details</a>
</div>
</div>
<div class="box">
<div class="image">
<a href="#"><img src="https://dummyimage.com/80x80/000/fff"></a>
<a href="#">Lorem ipsum dolor sit amet, consectetur adipisicing dolor sit amet, consectetur.</a>
</div>
<div class="tools">
<a href="#">View details</a>
</div>
</div>
我需要的是产生以下结果的查询:
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的状态,无论它是否发生。如果不是,则显示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
,否则显示new
。
答案 0 :(得分:1)
您想知道记录的日期是否是用户的最短日期:
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()
。
答案 1 :(得分:1)
答案 2 :(得分:1)
尝试以下方法: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
答案 3 :(得分:0)
您可以简单地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
答案 4 :(得分:0)
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 )