关于SQL面试题

题目如下:

员工表tl_employee

(

com_emp_id int(6) notnull pk,

name varchar(30) notnull,

age number not null,

sex char(1)not null

….

);

假如数据量很大约1000万条;写一个你认为最高效的SQL,用一个SQL计算以下四种人:

sex =’男’ and age> 35

sex =’男’ and age< 35

sex =’女’ and age> 35

sex =’女’ and age< 35

每种员工的数量


解决方案1:

select count(t1.com_emp_id) as 大于35男士人数,
       count(t2.com_emp_id) as 小于35男士人数,
       count(t3.com_emp_id) as 大于35女士人数,
       count(t4.com_emp_id) as 小于35女士人数
  from tl_employee t
  left join tl_employee t1 on t1.com_emp_id = t.com_emp_id and t1.sex = '男' and t1.age > 35
  left join tl_employee t2 on t2.com_emp_id = t.com_emp_id and t2.sex = '男' and t2.age < 35
  left join tl_employee t3 on t3.com_emp_id = t.com_emp_id and t3.sex = '女' and t3.age > 35
  left join tl_employee t4 on t4.com_emp_id = t.com_emp_id and t4.sex = '女' and t4.age < 35

解决方案2:

select sum(case when sex = '男' and age > 35 then 1 else 0 end) as 大于35男士人数,
       sum(case when sex = '男' and age < 35 then 1 else 0 end) as 小于35男士人数,
       sum(case when sex = '女' and age > 35 then 1 else 0 end) as 大于35女士人数,
       sum(case when sex = '女' and age < 35 then 1 else 0 end) as 小于35女士人数
  from tl_employee


如果更好的方案请大家补充,谢谢!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值