当前位置:   article > 正文

做题记录-力扣 LeetCode-SQL_if(rating < 3, 1, 0)

if(rating < 3, 1, 0)

学习计划-SQL 入门

第 1 天 选择

595. 大的国家

  1. select name,population,area
  2. from World
  3. where area>=3000000 or population >=25000000
  4. ------------------------
  5. select name,population,area
  6. from World
  7. where area>=3000000
  8. UNION
  9. select name,population,area
  10. from World
  11. where population >=25000000

1757. 可回收且低脂的产品

  1. select product_id
  2. from Products
  3. where low_fats='Y' and recyclable ='Y'

584. 寻找用户推荐人

  1. = 或 != 只能判断基本数据类型 
  2. is 关键字只能判断null 
  • ifnull(referee_id,0)!=2
  1. select name
  2. from customer
  3. where referee_id!=2 or referee_id is null
  4. --------------------------
  5. select name
  6. from customer
  7. where referee_id<>2 or referee_id is null
  8. --------------------------
  9. #先把null转为0
  10. select name
  11. from customer
  12. where ifnull(referee_id,0)!=2;

183. 从不订购的客户

  1. select customers.name as customers
  2. from customers
  3. where id not in
  4. (select customers.id
  5. from customers,orders
  6. where customers.id=orders.customerid)
  7. --------------------------
  8. select Name as Customers
  9. from Customers
  10. where Id not in(select CustomerId
  11. from Orders)

第 2 天 排序 & 修改 

1873. 计算特殊奖金

  1. select employee_id,salary as bonus
  2. from Employees
  3. where (employee_id%2)!=0 and name not like "M%"
  4. union
  5. select employee_id,salary=0 as bonus
  6. from Employees
  7. where (employee_id%2)=0 or name like "M%"
  8. order by employee_id

627. 变更性别

Update 语句用于修改表中的数据。
UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值 

1

2

3

UPDATE table_name

SET column1=value1,column2=value2,...

WHERE column(1)=value(1),column(2)=value(2)...and column(n)=value(n);

  • case sex when 'm' then 'f' else 'm' end 
  1. update salary
  2. set sex =
  3. (
  4. case sex when 'm' then 'f' else 'm' end
  5. );

196. 删除重复的电子邮箱

DELETE 语句用于删除表中的行。
DELETE FROM 表名称 WHERE 列名称 = 值 

  1. delete a
  2. from Person a , Person b
  3. where a.id > b.id and a.email = b.email

第 3 天 字符串处理函数/正则

1667. 修复表中的名字

CONCAT() 函数
CONCAT 可以将多个字符串拼接在一起。

LEFT(str, length) 函数
从左开始截取字符串,length 是截取的长度。

UPPER(str) LOWER(str)
UPPER(str) 将字符串中所有字符转为大写

LOWER(str) 将字符串中所有字符转为小写

SUBSTRING(str, begin, end)
截取字符串,end 不写默认为空。

SUBSTRING(name, 2) 从第二个截取到末尾,注意并不是下标,就是第二个。

concat(upper(left(name,1)),lower(substr(name,2)))
  1. select user_id,
  2. concat(upper(left(name,1)),lower(substr(name,2))) as name
  3. from Users
  4. order by user_id

1484. 按日期分组销售产品

GROUP_CONCAT( [DISTINCT] 要连接的字段 [ORDER BY 排序字段 ASC/DESC] [separator ‘分隔符’] )

  1. select sell_date,
  2. count(distinct(product)) as num_sold,
  3. group_concat( distinct product separator ',') as products
  4. from Activities
  5. group by sell_date
  6. order by sell_date

1527. 患某种疾病的患者

  1. select *
  2. from Patients
  3. where conditions like "DIAB1%" or conditions like "% DIAB1%"

第 4 天 组合查询 & 指定选取

1965. 丢失信息的雇员

  1. select employee_id from employees
  2. where employee_id not in (select employee_id from salaries)
  3. union
  4. select employee_id from salaries
  5. where employee_id not in (select employee_id from employees)
  6. order by employee_id
  7. ------------------
  8. select e.employee_id
  9. from Employees e
  10. left join Salaries s
  11. on e.employee_id=s.employee_id
  12. where salary is null
  13. union
  14. select s.employee_id
  15. from Employees e
  16. right join Salaries s
  17. on e.employee_id=s.employee_id
  18. where name is null
  19. order by employee_id

1795. 每个产品在不同商店的价格

  •  行转列用groupby+sumif,列转行用union all
  • store1 as price from Products where store1 is not null
  1. select product_id,'store1' store, store1 as price from Products where store1 is not null
  2. union all
  3. select product_id,'store2' store, store2 as price from Products where store2 is not null
  4. union all
  5. select product_id,'store3' store, store3 as price from Products where store3 is not null

608. 树节点

  1. select id,
  2. case
  3. when id = (select id from tree where p_id is null) then 'Root'
  4. when id in (select p_id from tree) then 'Inner'
  5. else 'Leaf'
  6. end as Type
  7. from tree
  8. order by id
  9. --------------------------
  10. # 根节点:如果这个节点是整棵树的根,即没有父节点。
  11. select id, 'Root' as type from tree where p_id is null
  12. union all
  13. # 内部节点:如果这个节点既不是叶子节点也不是根节点。
  14. select id, 'Inner' as type
  15. from tree
  16. where p_id is not null and
  17. id in (select p_id from tree where p_id is not null)
  18. union all
  19. # 叶子节点:如果这个节点没有任何孩子节点。
  20. select id, 'Leaf' as type
  21. from tree
  22. where p_id is not null and
  23. id not in (select p_id from tree where p_id is not null)
  24. order by id

176. 第二高的薪水

  1. select ifnull((select distinct salary
  2. from Employee
  3. order by salary desc
  4. limit 1 offset 1) ,null)
  5. as SecondHighestSalary
  6. ----------------------
  7. select ifnull((select distinct Salary
  8. from Employee
  9. order by Salary desc
  10. limit 1,1),null)
  11. as SecondHighestSalary
  12. ----------------------
  13. select b.salary as SecondHighestSalary
  14. from Employee a
  15. left join Employee b
  16. on a.salary>b.salary
  17. order by a.salary desc,b.salary desc
  18. limit 1

第 5 天 合并

175. 组合两个表

//A inner join B                  取交集。 
//A left join B                     取 A 全部,B 没有对应的值为 null。 
//A right join B                   取 B 全部, A 没有对应的值为 null。
//A full outer join B            取并集,彼此没有对应的值为 null。 

对应条件在 on 后面填写

  1. select firstName,lastName,city,state
  2. from Person p
  3. left join Address a
  4. on p.personId = a.personId

1581. 进店却未进行过交易的顾客

  1. select customer_id,count(customer_id) as count_no_trans
  2. from Visits
  3. where visit_id not in (select visit_id from Transactions)
  4. group by customer_id

1148. 文章浏览 I

  1. select distinct author_id as id
  2. from Views
  3. where author_id=viewer_id
  4. order by id

第 6 天 合并

197. 上升的温度

DATEDIFF(expr1,expr2) 表示为从一个日期到另一个日期的天数。expr1 并且expr2是日期或日期和时间表达式。计算中仅使用值的日期部分。expr1 − expr2

  1. #截至 2019-07-27(含)的 30 天内
  2. datediff('2019-07-27',activity_date)<30
  3. activity_date BETWEEN '2019-06-28' AND '2019-07-27'
  1. select b.id as id
  2. from Weather a,Weather b
  3. where datediff(b.recordDate, a.recordDate) = 1 and b.Temperature>a.Temperature

607. 销售员

  1. select name
  2. from SalesPerson
  3. where sales_id not in (select sales_id
  4. from Company,Orders
  5. where Orders.com_id = Company.com_id
  6. and Company.name ='RED')
  7. -------------------------------------
  8. select name
  9. from SalesPerson
  10. where sales_id not in (select sales_id
  11. from Orders
  12. where com_id =(select com_id
  13. from Company
  14. where name='RED'))

第 7 天 计算函数

1141. 查询近30天活跃用户数

  1. select activity_date as day,count(distinct user_id) as active_users
  2. from Activity
  3. where activity_date between '2019-06-28' and '2019-07-27'
  4. group by activity_date
  5. -----------------------------
  6. #注意datediff(expr1,expr2)的顺序,为expr1 − expr2
  7. #数据中可能还有大于 7.27 号的数据,第十三组测试样例就有 2019-8-25 的数据,所以还要保证日期差大于等于0
  8. select activity_date as day,count(distinct user_id) as active_users
  9. from Activity
  10. where datediff('2019-07-27',activity_date)<30 and datediff('2019-07-27',activity_date)>=0
  11. group by activity_date

1693. 每天的领导和合伙人

  1. select date_id,make_name,count(distinct lead_id) as unique_leads,count(distinct partner_id) as unique_partners
  2. from DailySales
  3. group by date_id, make_name

1729. 求关注者的数量

  1. select user_id,count(distinct follower_id) as followers_count
  2. from Followers
  3. group by user_id
  4. order by user_id

第 8 天 计算函数

586. 订单最多的客户

  1. select customer_number
  2. from Orders
  3. group by customer_number
  4. order by count(order_number) desc
  5. limit 1

511. 游戏玩法分析 I

  1. select player_id,min(event_date) as first_login
  2. from Activity
  3. group by player_id

1890. 2020年最后一次登录

  1. select user_id,max(time_stamp) as last_stamp
  2. from Logins
  3. where year(time_stamp)=2020
  4. group by user_id
  5. -------------------------------
  6. select user_id,max(time_stamp) as last_stamp
  7. from Logins
  8. where time_stamp between'2020-01-01 00:00:00' and '2020-12-31 23:59:59'
  9. group by user_id

1741. 查找每个员工花费的总时间

  1. select event_day as day,emp_id,sum(out_time-in_time) as total_time
  2. from Employees
  3. group by emp_id,event_day

第 9 天 控制流

1393. 股票的资本损益

  1. select stock_name,
  2. sum(case when operation='buy' then -price
  3. else price end ) as 'capital_gain_loss'
  4. from Stocks
  5. group by stock_name

1407. 排名靠前的旅行者

  1. select name,sum(ifnull(distance,0)) as travelled_distance
  2. from Users
  3. left join Rides
  4. on Rides.user_id=Users.id
  5. group by user_id
  6. order by travelled_distance desc,name

1158. 市场分析 I

  1. select u.user_id as buyer_id ,u.join_date,ifnull(num,0) as orders_in_2019
  2. from Users u
  3. left join (select buyer_id,count(buyer_id) as num
  4. from Orders
  5. where year(order_date)=2019
  6. group by buyer_id) as b
  7. on u. user_id=b.buyer_id

第 10 天 过滤

182. 查找重复的电子邮箱

  1. select email as Email
  2. from Person
  3. group by email
  4. having count(id)>1

1050. 合作过至少三次的演员和导演

  1. select actor_id,director_id
  2. from ActorDirector
  3. group by actor_id,director_id
  4. having count(timestamp)>=3

1587. 银行账户概要 II

  1. select name,sum(amount) as balance
  2. from Transactions t
  3. left join Users u
  4. on u.account = t.account
  5. group by u.account
  6. having balance >10000

1084. 销售分析III

  1. select product_id,product_name
  2. from Product
  3. where product_id in(select product_id
  4. from Sales
  5. where sale_date between '2019-01-01' and '2019-03-31')
  6. and product_id not in(select product_id
  7. from Sales
  8. where sale_date not between '2019-01-01' and '2019-03-31')
  9. -----------------------------------
  10. select p.product_id, product_name
  11. from product p
  12. inner join sales s
  13. on p.product_id = s.product_id
  14. group by product_id
  15. having min(sale_date) >= '2019-01-01' and max(sale_date) <= '2019-03-31';

难度顺序:简单

181 577 596 

181. 超过经理收入的员工

  1. select e1.name as Employee
  2. from Employee e1, Employee e2
  3. where e1.managerId = e2.id and e1.salary > e2.salary
  4. ---------------------------------
  5. select a.name as Employee
  6. from Employee a
  7. left join Employee b
  8. on a.managerId = b.id
  9. where a.salary > b.salary

577. 员工奖金

  1. select e.name, b.bonus
  2. from Employee e
  3. left join Bonus b
  4. on e.empId=b.empId
  5. having bonus < 1000 or bonus is null

596. 超过5名学生的课

  1. select class
  2. from Courses
  3. group by class
  4. having count(distinct student)>=5

610 619 620 

610. 判断三角形

  1. select x, y, z,
  2. (case when x + y > z and x + z > y and z + y > x then 'Yes' else 'No' end) as triangle
  3. from Triangle

619. 只出现一次的最大数字

  1. select max(b.num) as num
  2. from (select num
  3. from MyNumbers
  4. group by num
  5. having count(num)=1) as b

620. 有趣的电影

  1. select *
  2. from cinema
  3. where description != 'boring' and id%2!=0
  4. order by rating desc

1068 1075 1179

1068.产品销售分析 I

  1. select product_name,year,price
  2. from Sales s
  3. left join Product p
  4. on p.product_id=s.product_id

1075.项目员工 I

  1. select project_id, round(avg(experience_years),2) as average_years
  2. from Project p
  3. left join Employee e
  4. on p.employee_id = e.employee_id
  5. group by project_id
  6. ---------------------
  7. select project_id,round(sum(experience_years)/count(experience_years),2) as average_years
  8. from Project p,Employee e
  9. where p.employee_id =e.employee_id
  10. group by project_id

1179.重新格式化部门表

力扣https://leetcode.cn/problems/reformat-department-table/solution/group-byben-zhi-lun-by-loverxp-7mgy/

  1. select id,
  2. sum(case month when 'Jan' then revenue end) as Jan_Revenue,
  3. sum(case month when 'Feb' then revenue end) as Feb_Revenue,
  4. sum(case month when 'Mar' then revenue end) as Mar_Revenue,
  5. sum(case month when 'Apr' then revenue end) as Apr_Revenue,
  6. sum(case month when 'May' then revenue end) as May_Revenue,
  7. sum(case month when 'Jun' then revenue end) as Jun_Revenue,
  8. sum(case month when 'Jul' then revenue end) as Jul_Revenue,
  9. sum(case month when 'Aug' then revenue end) as Aug_Revenue,
  10. sum(case month when 'Sep' then revenue end) as Sep_Revenue,
  11. sum(case month when 'Oct' then revenue end) as Oct_Revenue,
  12. sum(case month when 'Nov' then revenue end) as Nov_Revenue,
  13. sum(case month when 'Dec' then revenue end) as Dec_Revenue
  14. from Department
  15. group by id

1211 1251 1280

1211.查询结果的质量和占比

  1. # rating<3用于判断,小于3就是返回1,否则返回0。avg求平均就跟把10求和再除以行数是一样的结果。
  2. select query_name,
  3. round(avg(rating/position),2) as quality,
  4. round(avg(rating < 3) * 100,2) as poor_query_percentage
  5. from Queries
  6. group by query_name
  7. ----------------------------------
  8. select query_name,
  9. round(avg(rating/position),2) as quality,
  10. round(sum(if((rating < 3),1,0))/count(*)*100,2) as poor_query_percentage
  11. from Queries
  12. group by query_name
  13. -----------------------------
  14. select query_name,
  15. round(sum(rating/position)/count(result), 2) as quality,
  16. round(sum(case when rating<3 then 1 else 0 end)/count(rating)*100, 2) as poor_query_percentage
  17. from Queries
  18. group by query_name

1251.平均售价

  1. select p.product_id as product_id,
  2. round(sum(price*units)/sum(units),2) as average_price
  3. from Prices p
  4. left join UnitsSold u
  5. on u.product_id=p.product_id and purchase_date between start_date and end_date
  6. group by p.product_id

1280.学生们参加各科测试的次数

  1. select st.student_id,st.student_name,su.subject_name,count(e.subject_name ) as attended_exams
  2. from Students st
  3. join Subjects su
  4. left join Examinations e
  5. on st.student_id=e.student_id and e.subject_name =su. subject_name
  6. group by st.student_id,su.subject_name
  7. order by st.student_id,su.subject_name
  8. -----------------------
  9. select temp1.student_id, temp1.student_name, temp1.subject_name, ifnull(attended_exams,0) as attended_exams
  10. from (select student_id,student_name,subject_name
  11. from Students st,Subjects su) as temp1
  12. left join (select student_id,subject_name,count(student_id) as attended_exams
  13. from Examinations group by student_id,subject_name) as temp2
  14. on temp1.student_id=temp2.student_id and temp1.subject_name=temp2.subject_name
  15. group by student_id,subject_name
  16. order by student_id,subject_name

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/871987
推荐阅读
相关标签
  

闽ICP备14008679号