select a.dt ,sum(case when b.time1 = date_add(a.dt,1) then 1 else 0 end) as `uv_left_rate` from (select uid,min(date(in_time)) dt from tb_user_log group by uid having dt like '2021-11%') a left join (select uid,date(in_time) time1 from tb_user_log group by uid,time1 ) b on a.uid = b.uid group by dt order by dt存在什么问题
时间: 2024-03-07 11:50:17 浏览: 59
你这个 SQL 语句中的问题是在第1个子查询中,select 语句中的 dt 列不能直接使用 like 来进行过滤,因为 dt 列的数据类型是日期,不是字符串。正确的做法是使用 date_format 函数来将日期类型转换为字符串类型,然后再使用 like 进行比较,例如:
```
select uid, min(date(in_time)) dt
from tb_user_log
where date_format(in_time, '%Y-%m') = '2021-11'
group by uid
```
另外,你的第2个子查询中也存在问题,因为在 group by 子句中,uid 和 time1 两列都出现,但是 time1 列并没有做任何聚合函数的计算,这样会导致结果集中出现重复的 uid 和 time1 组合。正确的做法是只按照 uid 分组,例如:
```
select uid, date(in_time) time1
from tb_user_log
group by uid, time1
```
综上所述,修正后的 SQL 语句应该是这样的:
```
select a.dt, sum(case when b.time1 = date_add(a.dt, 1) then 1 else 0 end) as `uv_left_rate`
from (
select uid, min(date(in_time)) dt
from tb_user_log
where date_format(in_time, '%Y-%m') = '2021-11'
group by uid
) a
left join (
select uid, date(in_time) time1
from tb_user_log
group by uid, date(in_time)
) b on a.uid = b.uid
group by a.dt
order by a.dt
```
阅读全文