来源:https://zhuanlan.zhihu.com/p/150959652
13道sql,基本上覆盖了所有sql的核心点。
要求写出一下SQL语句
1、查询位于“华东”或“华南”地区的供应商的ID、公司名称、地区、城市和电话字段的值
select 供应商ID,公司名称,地区,城市,电话
from 供应商
where 地区 = “华东” OR 地区 = “华南”;
2、查询“10248”和“10254”号订单的订单ID、订单上所订购的产品的名称及其销售金额
join左连接与右连接
select 订单id,产品名称,(单价*数量*折扣) as 销售金额
from 订单明细 as a inner join 产品 as b on a.产品id=b.产品id
where a.订单id = 10245 OR a.订单id=10254;
3、查询单价大于20元的所有产品的产品名称、单价以及供应商的公司名称、电话
select 产品名称.单价,公司名称,电话
from 产品 as a inner join 供应商 as b on a.供应商ID = b.供应商ID
where 单价>20;
4、按运货商公司名称,统计1997年由各个运货商承运的订单的总数量
select count(订单ID) as 订单数
from (
select a.运货商ID,a.订单ID,a.公司名称
from 运货商 as a inner join 订单 as b on a.运货商ID=b.运货商ID
where b.YEAR('订单日期')=1997
)
as c group by c.公司名称;
5、找出按箱包装的产品名称
select 产品名称 from 产品 where 包装单位 = “箱”;
6、找出雇员郑建杰所有的订单并根据订单销售额排序
select 订单ID,sum(单间*数量) as 销售额
from 订单明细 as d inner join(
select 订单ID,雇员ID
from 订单 as a inner join 雇员 as b on a.雇员ID = b.雇员ID
where b.姓氏="郑" and b.名字=“- 建杰”
) as c on c.订单ID=d.订单ID
Order by a.销售额
select 订单ID,sum(单价*数量 ) as 销售额 from 订单明细 d from
( Select 订单ID,雇员ID from 订单 as a inner join
雇员 as b on a.雇员id=b.雇员id where b.姓氏=”郑” and b.名字=”建杰” ) c on d.订单ID = c. 订单ID order by 销售额;
7、计算销量前10位的订单明细,结果集返回订单ID,订单日期,公司名称,发货日期,销售额,并排序
select 订单ID,订单日期,公司名称,发货日期,(单价*数量) as 销售额
from 订单明细 as d inner join(
select * from 订单,客户
where 订单.客户ID = 客户.客户ID
)as c on d.订单ID = c.订单ID
Order by 销售额 limit 10;
select 公司名称,订单日期,订单ID,发货日期,(单价*数量)as 销售额 from 订单明细 as d inner join
(select * from 订单,客户 where 订单.客户ID = 客户.客户ID ) as c
on d.订单ID=c.订单IDorder by 销售额 limit 10;
8、查出订单总额超出5000的所有订单,客户名称,客户所在地区
select 订单ID,客户名称,地区
from 客户 as b inner join(
select 订单ID,产品ID,订单总额 from 订单 b inner join(
select 订单ID,产品ID,(单价*数量) as 订单总额
from 订单明细
where 订单总额>5000)a on a.订单ID = b.订单ID
) on 客户.客户ID=订单.客户ID;
9.查询所有订单中月份不是单数的订单
select 订单ID from where month("订购日期")%2=0;
10.找出在入职时已超过30岁的所有员工信息
select * from 雇员 where timestampdiff(interval=“year”,出生日期,雇佣日期)>30;
TIMESTAMPDIFF(单位,开始时间,结束时间) ==开始时间-结束时间,
eg。 TIMESTAMPDIFF(MINUTE,begin_time,IFNULL(over_time,NOW()))
注释 :如果over_time不为空则用现在时间 减去 begin_time,得到的值的单位为分钟
11.计算每一笔订单的发货期(从订购到发货),运货期(从发货到到货)的时常,并按照发货期从长到短的顺序进行排序。
select timestampdiff(interval =”day”,订购日期,发货日期) as 发货期 ,
timestampdiff(interval=”day”,发货日期,到货日期) as 运货期
order by 发货期;
12.建存储过程 pd_GetProducts找出所有单价大于30的产品(产品id、产品名称、产品类别、产品供应商、总销售量、总销售额 );入参:产品类别,供应商;当产品类别和供应商都为空的时候,nofilter
delimiter //存储过程
create procedure pd_GetProducts )
In 产品类别
In 供应商)
BEGIN
Select 产品ID,产品名称,产品类别,供应商名称,总销售量,总销售额
from (
select *
from 订单明细 as a inner join (
select 产品ID,类别ID,产品名称,类别名称
from 产品
where 产品.类别ID=商品类别.类别ID) b on a.产品ID=b.产品ID
) c inner join 供应商 on a.供应商ID= 供应商.供应商ID;
END //
Delimiter;
13、建视图,查询当日产品销售情况v_TodaySales,字段包括不限于:产品id、产品名称、产品类别、客户、运货商、销售量、销售额
Create view v_TodaySales as
select 产品id,产品名称,产品类别,公司名称as 客户,运货商,销售量,销售额
from 订单 as d inner join (
Select *
from 商品类别 as a inner join (
Select 产品ID ,订单ID,类别ID,数量 as 销售量,(单价*数量)as 销售额,产品名称
where 订单明细.产品ID=产品.产品ID and DAY(“订购日期”)=DAY(now()) b on a.类别ID=b.类别ID) as c on d.订单ID=c.订单ID;