如何在MySQL中使用SQL查找特定用户每天登录的信息?
我有一张这样的桌子。
+----------+---------------------+---------+
| login_id | login_date | user_id |
+----------+---------------------+---------+
| 8494 | 2016-03-01 00:00:00 | 20703 |
| 22403 | 2016-03-01 00:00:00 | 53473 |
| 23965 | 2016-03-01 00:00:00 | 79722 |
| 30173 | 2016-03-01 00:00:00 | 36396 |
| 34928 | 2016-03-02 00:00:00 | 20703 |
| 38740 | 2016-03-02 00:00:00 | 15758 |
| 42769 | 2016-03-02 00:00:00 | 79722 |
| 44364 | 2016-03-02 00:00:00 | 79722 |
| 45440 | 2016-03-03 00:00:00 | 20703 |
| 49050 | 2016-03-03 00:00:00 | 36396 |
| 50273 | 2016-03-03 00:00:00 | 79722 |
| 50344 | 2016-03-04 00:00:00 | 20703 |
| 51360 | 2016-03-04 00:00:00 | 20703 |
| 54404 | 2016-03-04 00:00:00 | 53473 |
| 61533 | 2016-03-04 00:00:00 | 79722 |
| 72852 | 2016-03-05 00:00:00 | 20703 |
| 74546 | 2016-03-05 00:00:00 | 38289 |
| 76487 | 2016-03-05 00:00:00 | 62529 |
| 82439 | 2016-03-05 00:00:00 | 36396 |
| 90006 | 2016-03-05 00:00:00 | 36396 |
| 90404 | 2016-03-06 00:00:00 | 20703 |
+----------+---------------------+---------+
答案就像是
user_id, consecutive
20703, 'YES'
53473, 'NO'
每天从2016-03-01 - 2016-03-06登录20703登录,但53473只登录了两次。范围将从整个表格的开始到结束。
答案 0 :(得分:2)
嗯,你可以这样做:
select user_id,
( count(distinct login_date) = cnt_ld ) as everyday_flag
from t cross join
(select count(distinct login_date) as cnt_ld
from t
) tt
group by user_id, tt.cnt_ld;
请注意,这会将用户与表中的所有日期进行比较。如果有一天没有登录而您仍想要包含那一天,那么请使用最大值减去最小值进行比较。
这也会返回一个“布尔”标志(实际为0或1)。您可以使用case
将其转换为'YES'
/ 'NO'
,但我发现该号码更易于使用。
答案 1 :(得分:1)
我在tbl中获取最大和最小日期然后如果每个用户ID的计数等于最大和最小日期之间的日期(+1天),那么它是连续登录否则否。
select t1.user_id,
case when count(*)=datediff(t2.maxdt, t2.mindt)+1
then 'YES' else 'NO' end as consecutive
from tbl t1
join (select max(login_date) as maxdt,
min(login_date) as mindt
from tbl) t2
group by t1.user_id
order by t1.user_id;
答案 2 :(得分:1)
我只需使用带有group by
表达式的case
来查找连续登录
select user_id,
case when count(distinct login_date) <> datediff(max(login_date), min(login_date))+1
then 'No' else 'Yes' end consecutive
from table t
group by user_id
如果您要查找具有开始日期到结束日期的连续登录的用户,那么您也可以通过cross joins
进行此操作。
select user_id, case when counts <> total_counts then 'No' else 'Yes' end consecutive
from (select t.user_id, count(distinct login_date) counts
from table t
group by t.user_id )t cross join (
select count(distinct login_date) total_counts from table) tt