SQL语句笔记

在left join语句中,左表过滤必须放where条件中,右表过滤必须放on条件中.

例题:你需要写一段 SQL 命令,筛选出过去一年中订单总量 少于10本 的 书籍 。
注意:不考虑 上架(available from)距今 不满一个月 的书籍。并且 假设今天是 2019-06-23 。

Books 表:
±--------±-------------------±---------------+
| book_id | name | available_from |
±--------±-------------------±---------------+
| 1 | “Kalila And Demna” | 2010-01-01 |
| 2 | “28 Letters” | 2012-05-12 |
| 3 | “The Hobbit” | 2019-06-10 |
| 4 | “13 Reasons Why” | 2019-06-01 |
| 5 | “The Hunger Games” | 2008-09-21 |
±--------±-------------------±---------------+

Orders 表:
±---------±--------±---------±--------------+
| order_id | book_id | quantity | dispatch_date |
±---------±--------±---------±--------------+
| 1 | 1 | 2 | 2018-07-26 |
| 2 | 1 | 1 | 2018-11-05 |
| 3 | 3 | 8 | 2019-06-11 |
| 4 | 4 | 6 | 2019-06-05 |
| 5 | 4 | 5 | 2019-06-20 |
| 6 | 5 | 9 | 2009-02-02 |
| 7 | 5 | 8 | 2010-04-13 |
±---------±--------±---------±--------------+

Result 表:
±----------±-------------------+
| book_id | name |
±----------±-------------------+
| 1 | “Kalila And Demna” |
| 2 | “28 Letters” |
| 5 | “The Hunger Games” |
±----------±-------------------+

select t1.book_id,name from Books t1 left join Orders t2
on t1.book_id=t2.book_id
and dispatch_date >= ‘2018-06-23’
where available_from < ‘2019-05-23’
group by t1.book_id
having ifnull(sum(quantity),0)<10;

假如有1,2,3,4,7,8月份的数据,7月份的累积前三个月工资应该是5,6,7月份工资
使用"rows 2 PRECEDING"计算的是3,4,7月份的工资
使用"range 2 PRECEDING"计算的是5,6,7月份的工资

Employee 表保存了一年内的薪水信息。
请你编写 SQL 语句,对于每个员工,查询他除最近一个月(即最大月)之外,剩下每个月的近三个月的累计薪水(不足三个月也要计算)。
结果请按 Id 升序,然后按 Month 降序显示。
输入:

IdMonthSalary
1120
2120
1230
2230
3240
1340
3360
1460
3470

输出:

IdMonthSalary
1390
1250
1120
2120
33100
3240

select id,month,
sum(salary) over(partition by id order by month range 2 preceding) as Salary
from Employee where (id,month) not in
(select id,max(month) from Employee group by id)
order by id , month desc;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值