如何获得经理,员工对输出?
How to get manager,employee pair output?
我只需要所需的输出,因为我在采访中发布了 below.This 问题。
Table结构:
create table #test
(
id int,
emp char,
roles char
)
insert into #test values(1,'A','M')
insert into #test values(2,'B','E')
insert into #test values(3,'C','E')
insert into #test values(4,'D','M')
insert into #test values(5,'E','E')
insert into #test values(6,'F','E')
insert into #test values(7,'G','M')
insert into #test values(8,'H','E')
insert into #test values(9,'I','E')
insert into #test values(10,'J','E')
Table:
根据 table ,我们已将员工安排给他的经理
M=经理
E=员工
注意:**经理角色下面的直接 Emp 角色是他们的员工
**例如:A 是 B、C 的经理,D 是 E、F 的经理
所需输出:
看看谁来回答!
这是一个聪明的问题,我想我以前从未见过。天哪,你实际上必须考虑创建输出的模式是什么。
对于那些看不到它的人,"M" 值位于对应 "E" 值的第一列中,然后是下一个 "M"。这在 SQL Server 2012+ 中更容易表达,但这是 SQL Server 2005 中的一种方法:
我很确定这不是他们想的方法:
select tlm.emp, t.emp
from test t cross apply
(select max(t2.id) as LastMId
from test t2
where t2.id <= t.id and t2.roles = 'M'
) tm join
test tlm
on tm.LastMId = tlm.id
where t.roles = 'E';
SQL Fiddle 是 here.
面试官注意:如果用这道题,把数据库换成SQLServer 2012+就可以了。该系统提供的功能还有更优雅的解决方案。
编辑:
这其实是我想写的版本:
select tm.emp, t.emp
from test t cross apply
(select top 1 t2.emp
from test t2
where t2.id <= t.id and t2.roles = 'M'
order by t2.id desc
) tm
where t.roles = 'E';
任何 SQL 服务器版本的另一种方法:
select t1.emp, t2.emp
from
(
select id,
case
when t.roles = 'E' then (select emp from #test where id = (select max(id) from #test where id < t.id and roles = 'M'))
end as emp
from #test t) t1
join
#test t2 on t1.Id = t2.Id
where t1.emp is not null
我只需要所需的输出,因为我在采访中发布了 below.This 问题。
Table结构:
create table #test
(
id int,
emp char,
roles char
)
insert into #test values(1,'A','M')
insert into #test values(2,'B','E')
insert into #test values(3,'C','E')
insert into #test values(4,'D','M')
insert into #test values(5,'E','E')
insert into #test values(6,'F','E')
insert into #test values(7,'G','M')
insert into #test values(8,'H','E')
insert into #test values(9,'I','E')
insert into #test values(10,'J','E')
Table:
根据 table ,我们已将员工安排给他的经理
M=经理
E=员工
注意:**经理角色下面的直接 Emp 角色是他们的员工
**例如:A 是 B、C 的经理,D 是 E、F 的经理
所需输出:
看看谁来回答!
这是一个聪明的问题,我想我以前从未见过。天哪,你实际上必须考虑创建输出的模式是什么。
对于那些看不到它的人,"M" 值位于对应 "E" 值的第一列中,然后是下一个 "M"。这在 SQL Server 2012+ 中更容易表达,但这是 SQL Server 2005 中的一种方法:
我很确定这不是他们想的方法:
select tlm.emp, t.emp
from test t cross apply
(select max(t2.id) as LastMId
from test t2
where t2.id <= t.id and t2.roles = 'M'
) tm join
test tlm
on tm.LastMId = tlm.id
where t.roles = 'E';
SQL Fiddle 是 here.
面试官注意:如果用这道题,把数据库换成SQLServer 2012+就可以了。该系统提供的功能还有更优雅的解决方案。
编辑:
这其实是我想写的版本:
select tm.emp, t.emp
from test t cross apply
(select top 1 t2.emp
from test t2
where t2.id <= t.id and t2.roles = 'M'
order by t2.id desc
) tm
where t.roles = 'E';
任何 SQL 服务器版本的另一种方法:
select t1.emp, t2.emp
from
(
select id,
case
when t.roles = 'E' then (select emp from #test where id = (select max(id) from #test where id < t.id and roles = 'M'))
end as emp
from #test t) t1
join
#test t2 on t1.Id = t2.Id
where t1.emp is not null