简体   繁体   English

自加入SQL而不聚合

[英]self joining sql without aggregation

I have a table with the below structure: 我有一个具有以下结构的表:

    ID   EmployeeType   Name
    1     Contract      John, Baxter
    2     Contract      Will, Smith
    3     Full          Josh, Stevens
    4     Full          Sitar, Zhang

All I need to do is Pivot it so I get the below output: 我需要做的就是将其透视,所以我得到以下输出:

      Contract_Employee   FullTime_Employee
      John, Baxter        Josh, Stevens
      Will,Smith          Sitar, Zhang

Any idea how I can do this in one query? 知道如何在一个查询中做到这一点吗?

That's kind of a funny request. 这是一个有趣的请求。 Here's how I would do it: (basically, just deriving a fake key to "join" on for two derived tables, on for contractors, one for employees) 这是我的操作方式:(基本上,只是派生一个假密钥来“联接”两个派生表,一个用于承包商,一个用于雇员)

    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

One method of doing this is to use aggregation: 一种方法是使用聚合:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM