【高频SQL基础50题】11-15
迷迷糊糊,debug又一天。
目录
1.查询近30天活跃用户数
2.员工的直属部门
3.换座位
4.患某种疾病的患者
5.大的国家
1.查询近30天活跃用户数
排序和分组题。
# Write your MySQL query statement below
SELECT activity_date AS day,count(DISTINCT user_id) AS active_users
FROM Activity
WHERE DATEDIFF("2019-07-27",activity_date) BETWEEN 0 AND 29
#排序
GROUP BY activity_date
2.员工的直属部门
高级查询和连接。
这里的max使用非常好,因为结果必然存在。
# Write your MySQL query statement below
SELECT
employee_id,IF(COUNT(department_id)=1,department_id,MAX(CASE primary_flag WHEN 'Y' THEN department_id END)) AS department_id
FROM Employee
GROUP BY employee_id
ps:
case when要搭配聚合函数使用
3.换座位
子查询。
我开始的思路是调换名字,后面发现改动id比较快,排序后重新编号即可。
# Write your MySQL query statement below
SELECT @id:=@id+1 AS id,student FROM seat,(SELECT @id:=0) AS val ORDER BY CASE WHEN id%2=0 THEN id ELSE id +2 END;
ps:
4.患某种疾病的患者
高级字符串表达式。
# Write your MySQL query statement below
SELECT *
FROM PATIENTS
WHERE CONDITIONS REGEXP '^DIAB1|\\sDIAB1';
5.大的国家
查询题。
# Write your MySQL query statement below
SELECT name,population,area FROM world WHERE population>=25000000
UNION
SELECT name,population,area FROM world WHERE area>=3000000;
ps: or和union