暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

MYSQL之进阶实战笔试题(二)

奈奈八尾 2021-04-19
359

现有一表user_login_table代表表名

user_name代表用户ID

date代表用户登录时间

其结构数据如下:


例题2:统计每天的访问量


思路一:将年月日分别查询出来在通过group by 年月日然后count distinct

具体代码如下:

select year(date) as year1,

        month(date) as month1,

        day(date) as day1,

        count(distinct(user_name))

from user_login_table

group by year1,month1,day1;


思路二:通过cast函数得到日期后通过group by 然后 count  distinct

具体代码如下:

select cast(date as date) as date1,

        count(distinct(user_name))

from user_login_table

group by date1;



例题3:统计前20%的数据记录的user_name


思路一:通过row_number函数新建一列自增数据,在通过where条件判断低于20%的列

具体代码如下:

select date1

from(select date(date) as date1,

                  row_number() over ( order by date desc) as rn

         from user_login_table ) a

where rn<=((select count(*) from user_login_table)*0.1);


思路二:通过mysql中的用户变量(@)自增一列数据,在通过where条件判断低于20%的列

具体代码如下:

select date1

from (select date(date) date1,

                   @number:=@number+1 as num

            from user_login_table a,(select @number:=0) b

          order by date1 desc) a

where num<=((select count(*) from user_login_table)*0.1) ;


用户变量知识内容请参考以下文章

《https://www.jb51.net/article/201843.htm》





文章转载自奈奈八尾,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论