<!DOCTYPE html>
<html lang="zh-Hans">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="renderer" content="webkit">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=5">
    <title>【SQL取数练习，入门篇】牛客网SQL入门板块个人练习，含sql文件，复习必备 | 云图网</title>
    <meta name="keywords" content="device,id,profile,question,SQL,university,USER,牛客,练习">
<meta name="description" content="文章目录 数据表介绍1： 练习1：入门（简单） 数据表介绍2： 练习2：入门（基础） 入门(文本)   数据表介绍1： 用户信息表：user_profile其中device_id指终端编号（每个用户有唯一的一个终端），gender指性别，age指年龄，university指用户所在的学校，gpa是该用户平均学分绩点，a…">
<meta property="og:type" content="article">
<meta property="og:url" content="https://blog.ytso.com/tech/bigdata/275859.html">
<meta property="og:site_name" content="云图网">
<meta property="og:title" content="【SQL取数练习，入门篇】牛客网SQL入门板块个人练习，含sql文件，复习必备">
<meta property="og:image" content="http://ytso-blog-oss-img.oss-accelerate.aliyuncs.com/wp-content/uploads/2022/07/21/20220721175738252.jpg">
<meta property="og:description" content="文章目录 数据表介绍1： 练习1：入门（简单） 数据表介绍2： 练习2：入门（基础） 入门(文本)   数据表介绍1： 用户信息表：user_profile其中device_id指终端编号（每个用户有唯一的一个终端），gender指性别，age指年龄，university指用户所在的学校，gpa是该用户平均学分绩点，a…">
<link rel="canonical" href="https://blog.ytso.com/tech/bigdata/275859.html">
<meta name="applicable-device" content="pc,mobile">
<meta http-equiv="Cache-Control" content="no-transform">
<link rel="shortcut icon" href="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg">
<link rel='dns-prefetch' href='//cdnjs.cloudflare.com' />
<style id='wp-img-auto-sizes-contain-inline-css' type='text/css'>
img:is([sizes=auto i],[sizes^="auto," i]){contain-intrinsic-size:3000px 1500px}
/*# sourceURL=wp-img-auto-sizes-contain-inline-css */
</style>
<link rel='stylesheet' id='stylesheet-css' href='https://blog.ytso.com/wp-content/themes/justnews/css/style.css?ver=6.21.5' type='text/css' media='all' />
<link rel='stylesheet' id='material-icons-css' href='https://blog.ytso.com/wp-content/themes/justnews/themer/assets/css/material-icons.css?ver=6.21.5' type='text/css' media='all' />
<link rel='stylesheet' id='remixicon-css' href='https://cdnjs.cloudflare.com/ajax/libs/remixicon/4.2.0/remixicon.min.css?ver=6.9.4' type='text/css' media='all' />
<link rel='stylesheet' id='font-awesome-css' href='https://blog.ytso.com/wp-content/themes/justnews/themer/assets/css/font-awesome.css?ver=6.21.5' type='text/css' media='all' />
<style id='wp-block-library-inline-css' type='text/css'>
:root{--wp-block-synced-color:#7a00df;--wp-block-synced-color--rgb:122,0,223;--wp-bound-block-color:var(--wp-block-synced-color);--wp-editor-canvas-background:#ddd;--wp-admin-theme-color:#007cba;--wp-admin-theme-color--rgb:0,124,186;--wp-admin-theme-color-darker-10:#006ba1;--wp-admin-theme-color-darker-10--rgb:0,107,160.5;--wp-admin-theme-color-darker-20:#005a87;--wp-admin-theme-color-darker-20--rgb:0,90,135;--wp-admin-border-width-focus:2px}@media (min-resolution:192dpi){:root{--wp-admin-border-width-focus:1.5px}}.wp-element-button{cursor:pointer}:root .has-very-light-gray-background-color{background-color:#eee}:root .has-very-dark-gray-background-color{background-color:#313131}:root .has-very-light-gray-color{color:#eee}:root .has-very-dark-gray-color{color:#313131}:root .has-vivid-green-cyan-to-vivid-cyan-blue-gradient-background{background:linear-gradient(135deg,#00d084,#0693e3)}:root .has-purple-crush-gradient-background{background:linear-gradient(135deg,#34e2e4,#4721fb 50%,#ab1dfe)}:root .has-hazy-dawn-gradient-background{background:linear-gradient(135deg,#faaca8,#dad0ec)}:root .has-subdued-olive-gradient-background{background:linear-gradient(135deg,#fafae1,#67a671)}:root .has-atomic-cream-gradient-background{background:linear-gradient(135deg,#fdd79a,#004a59)}:root .has-nightshade-gradient-background{background:linear-gradient(135deg,#330968,#31cdcf)}:root .has-midnight-gradient-background{background:linear-gradient(135deg,#020381,#2874fc)}:root{--wp--preset--font-size--normal:16px;--wp--preset--font-size--huge:42px}.has-regular-font-size{font-size:1em}.has-larger-font-size{font-size:2.625em}.has-normal-font-size{font-size:var(--wp--preset--font-size--normal)}.has-huge-font-size{font-size:var(--wp--preset--font-size--huge)}.has-text-align-center{text-align:center}.has-text-align-left{text-align:left}.has-text-align-right{text-align:right}.has-fit-text{white-space:nowrap!important}#end-resizable-editor-section{display:none}.aligncenter{clear:both}.items-justified-left{justify-content:flex-start}.items-justified-center{justify-content:center}.items-justified-right{justify-content:flex-end}.items-justified-space-between{justify-content:space-between}.screen-reader-text{border:0;clip-path:inset(50%);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px;word-wrap:normal!important}.screen-reader-text:focus{background-color:#ddd;clip-path:none;color:#444;display:block;font-size:1em;height:auto;left:5px;line-height:normal;padding:15px 23px 14px;text-decoration:none;top:5px;width:auto;z-index:100000}html :where(.has-border-color){border-style:solid}html :where([style*=border-top-color]){border-top-style:solid}html :where([style*=border-right-color]){border-right-style:solid}html :where([style*=border-bottom-color]){border-bottom-style:solid}html :where([style*=border-left-color]){border-left-style:solid}html :where([style*=border-width]){border-style:solid}html :where([style*=border-top-width]){border-top-style:solid}html :where([style*=border-right-width]){border-right-style:solid}html :where([style*=border-bottom-width]){border-bottom-style:solid}html :where([style*=border-left-width]){border-left-style:solid}html :where(img[class*=wp-image-]){height:auto;max-width:100%}:where(figure){margin:0 0 1em}html :where(.is-position-sticky){--wp-admin--admin-bar--position-offset:var(--wp-admin--admin-bar--height,0px)}@media screen and (max-width:600px){html :where(.is-position-sticky){--wp-admin--admin-bar--position-offset:0px}}
/*wp_block_styles_on_demand_placeholder:69cba5b16ea46*/
/*# sourceURL=wp-block-library-inline-css */
</style>
<style id='classic-theme-styles-inline-css' type='text/css'>
/*! This file is auto-generated */
.wp-block-button__link{color:#fff;background-color:#32373c;border-radius:9999px;box-shadow:none;text-decoration:none;padding:calc(.667em + 2px) calc(1.333em + 2px);font-size:1.125em}.wp-block-file__button{background:#32373c;color:#fff;text-decoration:none}
/*# sourceURL=/wp-includes/css/classic-themes.min.css */
</style>
<link rel='stylesheet' id='wpcom-member-css' href='https://blog.ytso.com/wp-content/plugins/wpcom-member/css/style.css?ver=1.7.19' type='text/css' media='all' />
<script type="text/javascript" src="https://blog.ytso.com/wp-includes/js/jquery/jquery.min.js?ver=3.7.1" id="jquery-core-js"></script>
<script type="text/javascript" src="https://blog.ytso.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=3.4.1" id="jquery-migrate-js"></script>
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="https://blog.ytso.com/xmlrpc.php?rsd" />
<meta name='description' content='文章目录 数据表介绍1： 练习1：入门（简单） 数据表介绍2： 练习2：入门（基础） 入门(文本)   数据表介绍1： 用户信息表：user_profile其中device_id指终端编号（每个用户有唯一的一个终端），gender指性别，age…' />
<meta name='keywords' content='device,id,profile,question,SQL,university,USER,牛客,练习' />
<style>:root{--theme-color: #08c; --theme-hover: #07c; --logo-height: 32px; --logo-height-mobile: 26px; --menu-item-gap: 28px; --member-login-bg: url('https://blog.ytso.com/loginwall.jpg'); --header-bg-color: #fff; --header-bg-image: none; --theme-border-radius-s: 3px; --theme-border-radius-m: 5px; --theme-border-radius-l: 8px; --theme-border-radius-xl: 12px; --thumb-ratio-default: 480 / 300; --thumb-ratio-post: 480 / 300; --post-video-ratio: 860 / 482;}</style>
<link rel="icon" href="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg" sizes="32x32" />
<link rel="icon" href="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg" sizes="192x192" />
<link rel="apple-touch-icon" href="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg" />
<meta name="msapplication-TileImage" content="https://imgcdn.ytso.com/wp-content/uploads/2024/10/20241015181503433.jpg" />
    <!--[if lte IE 11]><script src="https://blog.ytso.com/wp-content/themes/justnews/js/update.js"></script><![endif]-->
</head>
<body class="wp-singular post-template-default single single-post postid-275859 single-format-standard wp-theme-justnews lang-cn el-boxed header-fixed">
<header class="header header-fluid">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" aria-label="menu">
                <span class="icon-bar icon-bar-1"></span>
                <span class="icon-bar icon-bar-2"></span>
                <span class="icon-bar icon-bar-3"></span>
            </button>
                        <div class="logo">
                <a href="https://blog.ytso.com/" rel="home">
                    <img src="https://imgcdn.ytso.com/wp-content/uploads/2021/12/20211207181156143.png" alt="云图网">
                </a>
            </div>
        </div>
        <div class="collapse navbar-collapse mobile-style-0">
            <nav class="primary-menu"><ul id="menu-justnews-footer-menu" class="nav navbar-nav wpcom-adv-menu"><li class="menu-item"><a href="https://blog.ytso.com/category/industrynews">业界资讯</a></li>
<li class="menu-item current-post-ancestor active menu-item-style menu-item-style-1 dropdown"><a target="_blank" href="https://blog.ytso.com/category/tech" class="dropdown-toggle">技术专区</a>
<ul class="dropdown-menu menu-item-wrap menu-item-col-5">
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/cloud">云计算</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/ai">人工智能</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/safety">信息安全</a></li>
	<li class="menu-item current-post-ancestor current-post-parent active"><a href="https://blog.ytso.com/category/tech/bigdata">大数据</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/dev">研发管理</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/webdev">大前端</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/opensource">开源</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/aiops">智能运维</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/pnotes">编程笔记</a></li>
	<li class="menu-item"><a href="https://blog.ytso.com/category/tech/wp">WordPress</a></li>
</ul>
</li>
<li class="menu-item"><a href="https://blog.ytso.com/category/enterprise-strategic-planning">企业战略规划</a></li>
<li class="menu-item"><a href="https://blog.ytso.com/category/download">下载专区</a></li>
<li class="menu-item"><a href="https://blog.ytso.com/category/it%e6%b1%9f%e6%b9%96%e5%8f%b2">江湖史</a></li>
<li class="menu-item"><a href="https://blog.ytso.com/category/notes">随笔记录</a></li>
</ul></nav>            <div class="navbar-action">
                <div class="navbar-search-icon j-navbar-search"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-search"></use></svg></i></div><form class="navbar-search" action="https://blog.ytso.com/" method="get" role="search"><div class="navbar-search-inner"><i class="wpcom-icon wi navbar-search-close"><svg aria-hidden="true"><use xlink:href="#wi-close"></use></svg></i><input type="text" name="s" class="navbar-search-input" autocomplete="off" maxlength="100" placeholder="输入关键词搜索..." value=""><button class="navbar-search-btn" type="submit" aria-label="搜索"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-search"></use></svg></i></button></div></form>                    <div id="j-user-wrap">
                        <a class="login" href="https://blog.ytso.com/login">登录</a>
                        <a class="login register" href="https://blog.ytso.com/register">注册</a>
                    </div>
                                            <a class="wpcom-btn btn-primary btn-xs publish" href="https://blog.ytso.com/contribute">
                            <i class="fa fa-edit"></i> 投稿                        </a>
                                </div>
        </div>
    </div><!-- /.container -->
</header>

<div id="wrap">    <div class="wrap container">
        <ol class="breadcrumb" vocab="https://schema.org/" typeof="BreadcrumbList"><li class="home" property="itemListElement" typeof="ListItem"><a href="https://blog.ytso.com" property="item" typeof="WebPage"><span property="name" class="hide">云图网</span>首页</a><meta property="position" content="1"></li><li property="itemListElement" typeof="ListItem"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-arrow-right-3"></use></svg></i><a href="https://blog.ytso.com/category/tech" property="item" typeof="WebPage"><span property="name">技术专区</span></a><meta property="position" content="2"></li><li property="itemListElement" typeof="ListItem"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-arrow-right-3"></use></svg></i><a href="https://blog.ytso.com/category/tech/bigdata" property="item" typeof="WebPage"><span property="name">大数据</span></a><meta property="position" content="3"></li></ol>        <main class="main">
                            <article id="post-275859" class="post-275859 post type-post status-publish format-standard hentry category-bigdata tag-device tag-id tag-profile tag-question tag-sql tag-university tag-user tag-15553 tag-11974 entry">
                    <div class="entry-main">
                                                                        <div class="entry-head">
                            <h1 class="entry-title">【SQL取数练习，入门篇】牛客网SQL入门板块个人练习，含sql文件，复习必备</h1>
                            <div class="entry-info">
                                                                <time class="entry-date published" datetime="2022-07-21T17:57:34+08:00" pubdate>
                                    2022年7月21日 17:57                                </time>
                                <span class="dot">•</span>
                                <a href="https://blog.ytso.com/category/tech/bigdata" rel="category tag">大数据</a>                                                            </div>
                        </div>
                        
                                                <div class="entry-content text-indent text-justify">
                            <div id="toc">
<p class="toc-title"><strong>文章目录</strong><span class="toc-controller toc-controller-show">[隐藏]</span></p>
<ul>
<li class="toc-level3"><a href="#toc_1">文章目录</a></li>
<li class="toc-level3"><a href="#toc_2">数据表介绍1：</a></li>
<li class="toc-level3"><a href="#toc_3">练习1：入门（简单）</a></li>
<li class="toc-level3"><a href="#toc_4">数据表介绍2：</a></li>
<li class="toc-level3"><a href="#toc_5">练习2：入门（基础）</a></li>
<li class="toc-level3"><a href="#toc_6">入门(文本)</a></li>
</ul>
</div>
<p></br></p>
<h3 id="toc_1">文章目录</h3>
<ul>
<ul>
<li><a href="https://editor.csdn.net/md?not_checkout=1&amp;spm=1001.2014.3001.5352&amp;articleId=125908126#1_1" rel="noopener">数据表介绍1：</a></li>
<li><a href="https://editor.csdn.net/md?not_checkout=1&amp;spm=1001.2014.3001.5352&amp;articleId=125908126#1_30" rel="noopener">练习1：入门（简单）</a></li>
<li><a href="https://editor.csdn.net/md?not_checkout=1&amp;spm=1001.2014.3001.5352&amp;articleId=125908126#2_89" rel="noopener">数据表介绍2：</a></li>
<li><a href="https://editor.csdn.net/md?not_checkout=1&amp;spm=1001.2014.3001.5352&amp;articleId=125908126#2_151" rel="noopener">练习2：入门（基础）</a></li>
<li><a href="https://editor.csdn.net/md?not_checkout=1&amp;spm=1001.2014.3001.5352&amp;articleId=125908126#_305" rel="noopener">入门(文本)</a></li>
</ul>
</ul>
<p> </p>
<h3 id="toc_2"><a id="1_1" rel="noopener"></a>数据表介绍1：</h3>
<p>用户信息表：user_profile<br />其中device_id指终端编号（每个用户有唯一的一个终端），gender指性别，age指年龄，university指用户所在的学校，gpa是该用户平均学分绩点，active_days_within_30是30天内的活跃天数。<br /><noscript><img decoding="async" alt="在这里插入图片描述" src="http://ytso-blog-oss-img.oss-accelerate.aliyuncs.com/wp-content/uploads/2022/07/21/20220721175738252.jpg"/></noscript><img decoding="async" alt="在这里插入图片描述" class="j-lazy" src="https://blog.ytso.com/wp-content/themes/justnews/themer/assets/images/lazy.png" data-original="http://ytso-blog-oss-img.oss-accelerate.aliyuncs.com/wp-content/uploads/2022/07/21/20220721175738252.jpg"/><br />建表：</p>
<pre><code>drop table if exists user_profile;
CREATE TEMP TABLE user_profile(
id int NOT NULL,
device_id int NOT NULL,
gender varchar(14) NOT NULL,
age int ,
university varchar(32) NOT NULL,
province varchar(32)  NOT NULL,
gpa float);
INSERT INTO user_profile VALUES(1,2138,'male',21,'北京大学','BeiJing',3.4);
INSERT INTO user_profile VALUES(2,3214,'male',null,'复旦大学','Shanghai',4.0);
INSERT INTO user_profile VALUES(3,6543,'female',20,'北京大学','BeiJing',3.2);
INSERT INTO user_profile VALUES(4,2315,'female',23,'浙江大学','ZheJiang',3.6);
INSERT INTO user_profile VALUES(5,5432,'male',25,'山东大学','Shandong',3.8);
INSERT INTO user_profile VALUES(1,2234,'male',21,'北京大学','BeiJing',3.2);
INSERT INTO user_profile VALUES(2,2235,'male',null,'复旦大学','Shanghai',3.8);
INSERT INTO user_profile VALUES(3,2236,'female',20,'复旦大学','Shanghai',3.5);
INSERT INTO user_profile VALUES(4,2237,'female',23,'浙江大学','ZheJiang',3.3);
INSERT INTO user_profile VALUES(5,2238,'male',25,'复旦大学','Shanghai',3.1);
INSERT INTO user_profile VALUES(6,2239,'male',25,'北京大学','BeiJing',3.6);
INSERT INTO user_profile VALUES(7,2240,'male',null,'清华大学','BeiJing',3.3);
INSERT INTO user_profile VALUES(8,2241,'female',null,'北京大学','BeiJing',3.7);
</code></pre>
<h3 id="toc_3"><a id="1_30" rel="noopener"></a>练习1：入门（简单）</h3>
<p>1.查看用户信息表中所有的数据：<br />select * from user_profile;</p>
<p>2.取出用户的设备id对应的性别、年龄和学校的数据：<br />select device_id,gender,age,university from user_profile;</p>
<p>3.取出学校的去重数据:<br />select distinct(university) from user_profile;</p>
<p>4.查看前2个用户明细设备ID数据:<br />select device_id from user_profile limit 2;</p>
<p>5.查看前2个用户明细设备ID数据，并将列名改为 ‘user_infos_example’:<br />select device_id as user_infos_example from user_profile limit 2;</p>
<p>6.筛选出所有北京大学的学生,返回设备id和学校:<br />select device_id,university from user_profile where university=‘北京大学’;</p>
<p>7.针对24岁以上的用户开展分析，取出满足条件的设备ID、性别、年龄、学校:<br />select device_id,gender,age,university from user_profile where age&gt;24;</p>
<p>8.针对20岁及以上且23岁及以下的用户开展分析，请你取出满足条件的设备ID、性别、年龄:<br />select device_id,gender,age from user_profile where age&gt;=20 and age&lt;=23;</p>
<p>9.查看除复旦大学以外的所有用户明细:<br />select device_id,gender,age,university from user_profile where university!=‘复旦大学’;</p>
<p>10.对用户的年龄分布开展分析，剔除没有获取到年龄的用户，取出所有年龄值不为空的用户的设备ID，性别，年龄，学校的信息：<br />select device_id,gender,age,university from user_profile where age is not null;</p>
<p>11.找到男性且GPA在3.5以上(不包括3.5)的用户进行调研：<br />select device_id,gender,age,university,gpa from user_profile where gender=‘male’ and gpa&gt;3.5;</p>
<p>12.到学校为北大或GPA在3.7以上(不包括3.7)的用户进行调研<br />select device_id,gender,age,university,gpa from user_profile where university=‘北京大学’ or gpa&gt;3.7;</p>
<p>13.找到学校为北大、复旦和山大的同学进行调研：<br />select device_id,gender,age,university,gpa from user_profile where university in (‘北京大学’,‘复旦大学’,‘山东大学’);</p>
<p>14.找到gpa在3.5以上(不包括3.5)的山东大学用户 或 gpa在3.8以上(不包括3.8)的复旦大学同学进行用户调研：<br />select device_id,gender,age,university,gpa from user_profile<br />where (gpa&gt;3.5 and university=‘山东大学’) or (gpa&gt;3.8 and university=‘复旦大学’);</p>
<p>15.查看所有大学中带有北京的用户的信息：<br />select device_id,age,university from user_profile where university like ‘%北京%’;</p>
<p>16.想要知道复旦大学学生gpa最高值是多少：<br />select max(gpa) from user_profile where university=‘复旦大学’;</p>
<p>17.看一下男性用户有多少人以及他们的平均gpa是多少:<br />select count(*) as male_num,avg(gpa) as avg_gpa from user_profile where gender=‘male’;</p>
<p>18.取出用户信息表中的用户年龄，请取出相应数据，并按照年龄升序排序:<br />select device_id,age from user_profile order by age asc;</p>
<p>19.取出用户信息表中的年龄和gpa数据，并先按照gpa升序排序，再按照年龄升序排序输出:<br />select device_id,gpa,age from user_profile order by gpa asc,age asc;</p>
<h3 id="toc_4"><a id="2_89" rel="noopener"></a>数据表介绍2：</h3>
<p>用户信息表 user_profile：其中device_id指终端编号（认为每个用户有唯一的一个终端），gender指性别，age指年龄，university指用户所在的学校，gpa是该用户平均学分绩点，active_days_within_30是30天内的活跃天数，question_cnt发帖数量字段，answer_cnt回答数量字段。<br />答题情况明细表 question_practice_detail：其中question_id是题目编号，result是答题结果。<br />试题难度程度表 question_detail：其中question_id是题目编号，difficult_level是题目的难度等级。<br />建表：</p>
<pre><code>drop table if exists user_profile;
drop table if  exists question_practice_detail;
drop table if  exists question_detail;
CREATE TEMP TABLE user_profile (
id int NOT NULL,
device_id int NOT NULL,
gender varchar(14) NOT NULL,
age int ,
university varchar(32) NOT NULL,
gpa float,
active_days_within_30 int ,
question_cnt int ,
answer_cnt int 
);
CREATE TEMP TABLE question_practice_detail (
id int NOT NULL,
device_id int NOT NULL,
question_id int NOT NULL,
result varchar(32) NOT NULL,
date date NOT NULL
);
CREATE TEMP TABLE question_detail (
id int NOT NULL,
question_idint NOT NULL,
difficult_level varchar(32) NOT NULL
);
INSERT INTO user_profile VALUES(1,2138,'male',21,'北京大学',3.4,7,2,12);
INSERT INTO user_profile VALUES(2,3214,'male',null,'复旦大学',4.0,15,5,25);
INSERT INTO user_profile VALUES(3,6543,'female',20,'北京大学',3.2,12,3,30);
INSERT INTO user_profile VALUES(4,2315,'female',23,'浙江大学',3.6,5,1,2);
INSERT INTO user_profile VALUES(5,5432,'male',25,'山东大学',3.8,20,15,70);
INSERT INTO user_profile VALUES(6,2131,'male',28,'山东大学',3.3,15,7,13);
INSERT INTO user_profile VALUES(7,4321,'male',28,'复旦大学',3.6,9,6,52);
INSERT INTO question_practice_detail VALUES(1,2138,111,'wrong','2021-05-03');
INSERT INTO question_practice_detail VALUES(2,3214,112,'wrong','2021-05-09');
INSERT INTO question_practice_detail VALUES(3,3214,113,'wrong','2021-06-15');
INSERT INTO question_practice_detail VALUES(4,6543,111,'right','2021-08-13');
INSERT INTO question_practice_detail VALUES(5,2315,115,'right','2021-08-13');
INSERT INTO question_practice_detail VALUES(6,2315,116,'right','2021-08-14');
INSERT INTO question_practice_detail VALUES(7,2315,117,'wrong','2021-08-15');
INSERT INTO question_practice_detail VALUES(8,3214,112,'wrong','2021-05-09');
INSERT INTO question_practice_detail VALUES(9,3214,113,'wrong','2021-08-15');
INSERT INTO question_practice_detail VALUES(10,6543,111,'right','2021-08-13');
INSERT INTO question_practice_detail VALUES(11,2315,115,'right','2021-08-13');
INSERT INTO question_practice_detail VALUES(12,2315,116,'right','2021-08-14');
INSERT INTO question_practice_detail VALUES(13,2315,117,'wrong','2021-08-15');
INSERT INTO question_practice_detail VALUES(14,3214,112,'wrong','2021-08-16');
INSERT INTO question_practice_detail VALUES(15,3214,113,'wrong','2021-08-18');
INSERT INTO question_practice_detail VALUES(16,6543,111,'right','2021-08-13');
INSERT INTO question_detail VALUES(1,111,'hard');
INSERT INTO question_detail VALUES(2,112,'medium');
INSERT INTO question_detail VALUES(3,113,'easy');
INSERT INTO question_detail VALUES(4,115,'easy');
INSERT INTO question_detail VALUES(5,116,'medium');
INSERT INTO question_detail VALUES(6,117,'easy');
</code></pre>
<h3 id="toc_5"><a id="2_151" rel="noopener"></a>练习2：入门（基础）</h3>
<p>20.了解2021年8月份所有练习过题目的总用户数和练习过题目的总次数:<br />select count(distinct device_id) did_cnt,count(question_id) question_cnt<br />from question_practice_detail<br />where month(date)=8;<br />– where date like “2021-08%”</p>
<p>21.对每个学校不同性别的用户活跃情况和发帖数量进行分析，计算出每个学校每种性别的用户数、30天内平均活跃天数和平均发帖数量:</p>
<pre><code>select gender,university, count(*) as user_num,
avg(active_days_within_30) as avg_active_day,
avg(question_cnt) as avg_question_cnt
from user_profile 
group by gender,university;
</code></pre>
<p>22.查看每个学校用户的平均发贴和回帖情况，寻找低活跃度学校进行重点运营，取出平均发贴数低于5的学校或平均回帖数小于20的学校:</p>
<pre><code>select university,
avg(question_cnt) as avg_question_cnt,
avg(answer_cnt) as avg_answer_cnt
from user_profile 
group by university
having avg_question_cnt&lt;5 or avg_answer_cnt&lt;20
</code></pre>
<p>23…查看不同大学的用户平均发帖情况，并期望结果按照平均发帖情况进行升序排列:</p>
<pre><code>select university,
avg(question_cnt) as avg_question_cnt
from user_profile 
group by university
order by avg_question_cnt asc;
</code></pre>
<p>24.查看所有来自浙江大学的用户题目回答明细情况:</p>
<pre><code>select a.device_id,question_id,result 
from question_practice_detail a 
left join user_profile b 
on a.device_id=b.device_id
where b.university='浙江大学'
</code></pre>
<p>25.了解每个学校答过题的用户平均答题数量情况,结果按照university升序排序。</p>
<pre><code>select university,
count(b.question_id)/count(distinct(b.device_id)) as avg_answer_cnt 
from user_profile a 
inner join question_practice_detail b on a.device_id=b.device_id
group by university
order by university asc;
</code></pre>
<p>26.计算一些参加了答题的不同学校、不同难度的用户平均答题量:<br />(结果在小数点位数保留4位，4位之后四舍五入)</p>
<pre><code>select a.university,c.difficult_level,
round(count(b.question_id)/count(distinct(b.device_id)),4)as avg_answer_cnt
from user_profile a 
inner join question_practice_detail b on a.device_id=b.device_id 
left join question_detail c on  b.question_id=c.question_id
group by university,difficult_level;
</code></pre>
<p>27.查看参加了答题的山东大学的用户在不同难度下的平均答题题目数<br />(结果在小数点位数保留4位，4位之后四舍五入)：</p>
<pre><code>select a.university,c.difficult_level,
round(count(b.question_id)/count(distinct(b.device_id)),4)as avg_answer_cnt
from user_profile a inner join question_practice_detail b on a.device_id=b.device_id 
left join question_detail c on  b.question_id=c.question_id
group by university,difficult_level
having a.university='山东大学';
</code></pre>
<p>28.查看学校为山东大学或者性别为男性的用户的device_id、gender、age和gpa数据:</p>
<pre><code>select device_id,gender,age,gpa from user_profile 
where university='山东大学' 
union all
select device_id,gender,age,gpa from user_profile
where gender='male';
</code></pre>
<p>29.将用户划分为25岁以下和25岁及以上两个年龄段，分别查看这两个年龄段用户数量<br />(age为null 也记为 25岁以下)</p>
<pre><code>select case when age&gt;=25 then  '25岁及以上' 
when age&lt;25 or age is null then '25岁以下'
end age_cut,count(*) number
from user_profile
group by age_cut;
</code></pre>
<p>30.将用户划分为20岁以下，20-24岁，25岁及以上三个年龄段，分别查看不同年龄段用户的明细情况，（若年龄为空请返回其他）:</p>
<pre><code>select device_id,gender, 
case when age&lt;20 then '20岁以下'
     when age between 20 and 24 then '20-24岁'
     when age&gt;=25 then '25岁及以上' 
     else '其他' 
     end age_cut
from user_profile;
</code></pre>
<p>31.计算出2021年8月每天用户练习题目的数量:</p>
<pre><code>select day(date) as day,
count(question_id) as question_cnt from 
question_practice_detail where 
date_format(date,"%Y-%m")="2021-08"
-- month(date)=8 and year(date)=2021
group by date
</code></pre>
<p>32.查看用户在某天刷题后第二天还会再来刷题的平均概率(用户的平均次日留存率)</p>
<pre><code>select COUNT(distinct b.device_id,date2) / COUNT(distinct a.device_id,date) as avg_ret 
from
-- date_add(date1, interval 1 day) -- 第二天来了
question_practice_detail as a
left join
(select device_id,date_add(date,interval 1 day) as date2 
 from question_practice_detail) as b 
on a.device_id=b.device_id and b.date2=a.date
</code></pre>
<p>33.取出每个学校的最低gpa：</p>
<pre><code>select device_id,university,gpa from user_profile
where (university,gpa) in 
(select university,min(gpa) from user_profile group by university)
order by university;
select device_id, university, gpa
from (
    select *,
    row_number() over (partition by university order by gpa) as rn
    from user_profile
) as univ_min
where rn=1
order by university;

</code></pre>
<p>34.了解复旦大学的每个用户在8月份练习的总题目数和回答正确的题目数情况，对于在8月份没有练习过的用户，答题数结果返回0</p>
<pre><code>select a.device_id, a.university, 
count(b.question_id) question_cnt, 
sum(if(b.result='right', 1, 0)) as right_question_cnt
from user_profile a left join question_practice_detail b 
on a.device_id=b.device_id and month(b.date)=8
where a.university='复旦大学'
group by a.device_id;
</code></pre>
<p>35.了解浙江大学的用户在不同难度题目下答题的正确率情况，按照准确率升序输出。</p>
<pre><code>select c.difficult_level,sum(if(b.result='right',1,0))/count(b.question_id) as correct_rate 
-- avg(if(b.result='right',1,0)) as correct_rate
from user_profile a left join question_practice_detail b on a.device_id=b.device_id
left join question_detail c on b.question_id=c.question_id
where a.university='浙江大学'
group by c.difficult_level
having c.difficult_level !='None' -- 为了防止结果中有难度为None的结果
order by correct_rate asc;
</code></pre>
<h3 id="toc_6"><a id="_305" rel="noopener"></a>入门(文本)</h3>
<p>运营举办了一场比赛，收到了一些参赛申请：</p>
<pre><code>drop table if exists user_submit;
CREATE TEMP TABLE user_submit (
id int NOT NULL,
device_id int NOT NULL,
profile varchar(100) NOT NULL,
blog_url varchar(100) NOT NULL
);
INSERT INTO user_submit VALUES(1,2138,'180cm,75kg,27,male','http:/url/bisdgboy777');
INSERT INTO user_submit VALUES(1,3214,'165cm,45kg,26,female','http:/url/dkittycc');
INSERT INTO user_submit VALUES(1,6543,'178cm,65kg,25,male','http:/url/tigaer');
INSERT INTO user_submit VALUES(1,4321,'171cm,55kg,23,female','http:/url/uhsksd');
INSERT INTO user_submit VALUES(1,2131,'168cm,45kg,22,female','http:/url/sysdney');

</code></pre>
<p>36.统计每个性别的用户分别有多少参赛者</p>
<pre><code>select substring_index(profile,',',-1) as gender,
-- if(profile like '%female','female','male') gender,
count(device_id) as number
from user_submit
group by gender;
</code></pre>
<p>37.把用户的个人博客用户字段提取出单独记录为一个新的字段：<br />(blog_url字段中url字符后的字符串为用户个人博客的用户名）</p>
<pre><code>-- 字段切割法 substring_index(string, '切割标志', 位置数（负号：从后面开始）)
-- device_id,substring_index(blog_url,'/',-1) as user_name
-- 替换法 replace(string, '被替换部分','替换后的结果')
-- device_id, replace(blog_url,'http:/url/','') as user_name -- 删除法 trim('被删除字段' from 列名)
-- device_id, trim('http:/url/' from blog_url) as user_name
-- 截取法 substr(string, start_point, length*截取长度*)
select device_id, substr(blog_url,11,length(blog_url)-10) as user_nam
from user_submit;
</code></pre>
<p>38.统计每个年龄的用户分别有多少参赛者：</p>
<pre><code>select substring_index(substring_index(profile,',',3),',',-1) age,
count(device_id) as number
from user_submit
group by (age)</code></pre>
<div class="entry-readmore"><div class="entry-readmore-btn"></div></div>                                                        <div class="entry-copyright"><p>原创文章，作者：1402239773，如若转载，请注明出处：https://blog.ytso.com/tech/bigdata/275859.html</p></div>                        </div>

                        <div class="entry-tag"><a href="https://blog.ytso.com/tag/device" rel="tag">device</a><a href="https://blog.ytso.com/tag/id" rel="tag">id</a><a href="https://blog.ytso.com/tag/profile" rel="tag">profile</a><a href="https://blog.ytso.com/tag/question" rel="tag">question</a><a href="https://blog.ytso.com/tag/sql" rel="tag">SQL</a><a href="https://blog.ytso.com/tag/university" rel="tag">university</a><a href="https://blog.ytso.com/tag/user" rel="tag">USER</a><a href="https://blog.ytso.com/tag/%e7%89%9b%e5%ae%a2" rel="tag">牛客</a><a href="https://blog.ytso.com/tag/%e7%bb%83%e4%b9%a0" rel="tag">练习</a></div>
                        <div class="entry-action">
                            <div class="btn-zan" data-id="275859"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-thumb-up-fill"></use></svg></i> 赞 <span class="entry-action-num">(0)</span></div>
                                                    </div>

                        <div class="entry-bar">
                            <div class="entry-bar-inner">
                                                                <div class="entry-bar-info entry-bar-info2">
                                    <div class="info-item meta">
                                                                                    <a class="meta-item j-heart" href="javascript:;" data-id="275859"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-star"></use></svg></i> <span class="data">0</span></a>                                        <a class="meta-item" href="#comments"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-comment"></use></svg></i> <span class="data">0</span></a>                                                                            </div>
                                    <div class="info-item share">
                                                                                    <a class="meta-item mobile j-mobile-share" href="javascript:;" data-id="275859" data-qrcode="https://blog.ytso.com/tech/bigdata/275859.html">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-share"></use></svg></i> 生成海报                                            </a>
                                                                                    <a class="meta-item wechat" data-share="wechat" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-wechat"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item weibo" data-share="weibo" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-weibo"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item qq" data-share="qq" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-qq"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item qzone" data-share="qzone" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-qzone"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item douban" data-share="douban" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-douban"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item linkedin" data-share="linkedin" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-linkedin"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item facebook" data-share="facebook" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-facebook"></use></svg></i>                                            </a>
                                                                                    <a class="meta-item twitter" data-share="twitter" target="_blank" rel="nofollow noopener noreferrer" href="#">
                                                <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-twitter"></use></svg></i>                                            </a>
                                                                            </div>
                                    <div class="info-item act">
                                        <a href="javascript:;" id="j-reading"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-article"></use></svg></i></a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                                            <div class="entry-page">
                    <div class="entry-page-prev entry-page-nobg">
                <a href="https://blog.ytso.com/tech/bigdata/275858.html" title="sql中pivot函数(行转列),unpivot(列转行)" rel="prev">
                    <span>sql中pivot函数(行转列),unpivot(列转行)</span>
                </a>
                <div class="entry-page-info">
                    <span class="pull-left"><i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-arrow-left-double"></use></svg></i> 上一篇</span>
                    <span class="pull-right">2022年7月21日 17:57</span>
                </div>
            </div>
                            <div class="entry-page-next entry-page-nobg">
                <a href="https://blog.ytso.com/tech/bigdata/275860.html" title="SQLite 建表、增删改查 简单操作" rel="next">
                    <span>SQLite 建表、增删改查 简单操作</span>
                </a>
                <div class="entry-page-info">
                    <span class="pull-right">下一篇 <i class="wpcom-icon wi"><svg aria-hidden="true"><use xlink:href="#wi-arrow-right-double"></use></svg></i></span>
                    <span class="pull-left">2022年7月21日 17:57</span>
                </div>
            </div>
            </div>
                                        <error>
    <code>wp_die</code>
    <title><![CDATA[WordPress &amp;rsaquo; Error]]></title>
    <message><![CDATA[&lt;h1&gt;Error establishing a Redis connection&lt;/h1&gt;
&lt;p&gt;To disable Redis, delete the &lt;code&gt;object-cache.php&lt;/code&gt; file in the &lt;code&gt;/wp-content/&lt;/code&gt; directory.&lt;/p&gt;
]]></message>
    <data>
        <status>500</status>
    </data>
</error>
<!--
Performance optimized by Redis Object Cache. Learn more: https://wprediscache.com

Retrieved 1917 objects (330 KB) from Redis using Predis (v2.4.0).
-->
