拼多多笔试题
据说是拼多多的面试题,刚帮人解决的。。。
题目一:
今天帮人看的sql题目,要求见上图:
;with tb_info(CLASS,TEACHER,COURSE) as (
select '1','A','MATH'
UNION ALL
select '1','A','SPORTS'
UNION ALL
SELECT '1','B','LANGUAGE'
UNION ALL
SELECT '2','A','MATH'
UNION ALL
SELECT '3','B','MATH'
UNION ALL
SELECT '4','B','LANGUAGE'
UNION ALL
SELECT '5','A','SPORTS'
UNION ALL
SELECT '6','B','LANGUAGE'
UNION ALL
SELECT '6','C','MATH'
)
select t.teacher
,t.classNum
,count(distinct i.course) as courseNum
from tb_info i join (
select teacher,count(*) as classNum from (
select teacher,class
from tb_info
group by teacher,class
) temp
group by teacher having count(class) > 3
) t
on i.teacher = t.teacher
group by t.teacher,t.classNum
题目二 求中位数:
declare @freq_num int
;with tb_record(num,freq) as(
select 1,9
union ALL
select 2,2
union ALL
select 4,3
union ALL
select 6,1
union ALL
select 7,2
union ALL
select 9,1
)
, temp as (
select num,freq
,(select sum(freq) from tb_record sub where sub.num<=t.num) as ord_num
from tb_record t
)
select @freq_num = sum(freq) from tb_record
declare @middle_digit int
declare @sql_cmd varchar(max)
set @middle_digit = @freq_num /2
if @freq_num %2 =0
BEGIN
set @sql_cmd = '
;with tb_record(num,freq) as(
select 1,9
union ALL
select 2,2
union ALL
select 4,3
union ALL
select 6,1
union ALL
select 7,2
union ALL
select 9,1
)
, temp as (
select num,freq
,(select sum(freq) from tb_record sub where sub.num<=t.num) as ord_num
from tb_record t
)
select sum(num)*1.0/2 from temp where temp.ord_num between '+cast(@middle_digit as varchar)+' and (select top 1 ord_num from temp t where t.ord_num>'+cast(@middle_digit as varchar)+')'
print @sql_cmd
exec(@sql_cmd)
END
;with tb_record(num,freq) as(
select 1,9
union ALL
select 2,2
union ALL
select 4,3
union ALL
select 6,1
union ALL
select 7,2
union ALL
select 9,1
)
, temp as (
select num,freq
,(select sum(freq) from tb_record sub where sub.num<=t.num) as ord_num
from tb_record t
)
select sum(num)*1.0/2 from temp
where ord_num between (select max(ord_num)/2 from temp)
and (select min(ord_num) from temp where ord_num>(select max(ord_num)/2 from temp))
如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。