SQL查询第三次训练(重点关照对象)

1,统计各部门男员工,女员工的最高薪资 (员工)

   select 部门,if(性别=-1 or 性别='False','女','男') as 性别,max(目前薪资) as 最高薪资 from 员工
   group by 部门,性别 

2、统计各部门平均年龄(员工)

select 部门,format(avg(year(now())-year(出生日期)),2) as 平均年龄 from 员工 group by 部门

3、统计超过666人的部门(员工)

select 部门,count(部门) as 人数 from 员工 group by 部门 having 人数>666

4.查询员工表中年龄最大的员工信息

select 员工编号,姓名,出生日期 from 员工 where 出生日期=(select min(出生日期) from 员工)

select 员工编号,姓名,出生日期 from 员工 order by 出生日期 limit 1

5.查询员工表中各部门年龄最小的员工信息(难)

select  distinct a.姓名,a.部门,a.出生日期 from 员工 a  where 
a.出生日期=(select max(出生日期) from 员工 b where b.部门=a.部门 ) 

select  distinct a.姓名,a.部门,a.出生日期 from 员工 a  inner join 
(select 部门,max(出生日期) as 出生日期  from 员工 group by 部门) b on a.部门=b.部门 where a.出生日期=b.出生日期


select  distinct a.姓名,a.部门,a.出生日期 from 员工 a  inner join 
(select 部门,max(出生日期) as 出生日期  from 员工 group by 部门) b on a.出生日期=b.出生日期 
  1. 查询有哪些员工姓名是重复的并显示重复姓名的人数
select 姓名,count(*) as 同名人数 from 员工 group by 姓名 having 同名人数>2

7.查询比平均单价高的产品的名称和单价(产品资料)

select 产品,单价 from 产品资料 where 单价>(select avg(单价) from 产品资料)

12、查询哪些公司没有采购(客户,订货主档)

select 客户编号,公司名称 from 客户 where 客户编号 not in (select distinct 客户编号 from 订货主档)

select a.客户编号,a.公司名称 from 客户 a left join 订货主档 b on a.客户编号=b.客户编号
where b.订单号码 is null

13、查询销售数量最多的产品信息(产品资料,订货明细)

select 产品编号,产品 from 产品资料  where 产品编号=销售数量最多的那个产品编号

如何求销售数量最多的那个产品编号?

select  产品编号,sum(数量) as 数量 from 订货明细 group by  产品编号 order by 数量 desc limit 1

最终代码:

select * from 产品资料  where 产品编号=(select  产品编号  from 订货明细 group by  产品编号 order by
 sum(数量) desc limit 1)

14、查询销售金额最多的产品信息(产品资料,訂貨明細)

select * from 产品资料  where 产品编号=(select  产品编号  from 订货明细 group by  产品编号 order by sum(单价*数量*(1-折扣)) desc limit 1)

15、查询出本月销售成单数量最多的前三名员工,并将其工资增加10%(訂貨主檔,员工)
本月销售成单数量最多的前三名员工

select 员工编号 from 订货主档 where month(now())= month(订单日期) group by 员工编号 order by  count(*) desc limit 3

16、查询1997年7月份客户采购的详细信息(客户 ,訂貨主檔 , 訂貨明細 )

select a.客户编号,a.公司名称,a.联系人,a.地址,b.订单号码,b.订单日期,b.收货人,
d.产品,e.类别名称,f.供应商,c.单价,c.数量,c.折扣 from 客户 a,订货主档 b,订货明细 c ,产品资料 d,产品类
别 e ,商品供应 f where a.客户编号=b.客户编号 and b.订单号码=c.订单号码 and c.产品编号=d.产品编号 and
 d.类别编号=e.类别编号 and d.供应商编号=f.供应商编号and 订单日期 between '1997-7-1' and '1997-7-31'

17、查询一个订单中采购金额最多的前三位公司详细信息(客户,訂貨主檔,訂貨明細)

select a.*
  from 客户 a, 订货主档 b
  where a.客户编号=b.客户编号 and
   b.订单号码 in (select * from  ( select 订单号码
                   from 订货明细
                   group by 订单号码
                   order by SUM(单价*数量*(1-折扣))  limit 3
                   ) t)

18.根据公司采购数量多少从高到低排列(訂貨主檔,訂貨明細)

select a.客户编号, sum(b.采购数量) as  采购总数量
from 订货主档 a,  (select 订单号码, SUM(数量) as 采购数量 from 订货明细 group by 订单号码) b
where a.订单号码=b.订单号码 
group by a.客户编号
order by 采购总数量 desc

19.统计各种产品类别的产品数量,按照产品类别数量从低到高显示(產品類別,产品资料)

  select a.类别名称, b.产品数量
  from 产品类别 a, ( select 类别编号, COUNT(*) as 产品数量 from 产品资料 group by 类别编号  ) b
  where a.类别编号=b.类别编号  
  order by b.产品数量 asc

20、统计各个城市中客户的人数(客户)

select 城市, COUNT(*) as 客户人数
  from 客户
  group by  城市
原文地址:https://www.cnblogs.com/James-221/p/13647442.html