我有一张包含以下结构的表格:
ID EmployeeType Name
1 Contract John, Baxter
2 Contract Will, Smith
3 Full Josh, Stevens
4 Full Sitar, Zhang
我需要做的就是转动它,以便得到以下输出:
Contract_Employee FullTime_Employee
John, Baxter Josh, Stevens
Will,Smith Sitar, Zhang
知道如何在一个查询中执行此操作吗?
答案 0 :(得分:0)
这是一个有趣的请求。这是我将如何做到的: (基本上,只需将假密钥导出到"加入"对于两个派生表,对于承包商,一个为员工)
CREATE TABLE #Table1
([ID] int, [EmployeeType] varchar(8), [Name] varchar(13))
;
INSERT INTO #Table1
([ID], [EmployeeType], [Name])
VALUES
(1, 'Contract', 'John, Baxter'),
(2, 'Contract', 'Will, Smith'),
(3, 'Full', 'Josh, Stevens'),
(4, 'Full', 'Sitar, Zhang'),
(5, 'Full','Bob, Bob'),
(6, 'Contract','Bob, Bob')
;
select
c.name as ContractEmployee,
f.name as FullTime_Employee
from
(
select
row_number() over (order by id) as RN,
name
from
#table1
where
employeetype = 'Contract'
) c
full join (
select
row_number() over (order by id) as RN,
name
from
#table1
where
employeetype = 'Full'
) f
on
c.name = f.name OR
c.rn = f.rn
答案 1 :(得分:0)
这样做的一种方法是使用聚合:
select max(case when employeetype = 'Contract' then Name end) as ContractEmployees,
max(case when employeetype = 'Full' then Name end) as FullEmployees
from (select t.*,
row_number() over (partition by employeetype order by id) as seqnum
from table t
) t
group by seqnum;