SQL Server - 从两行,一列到一行,两列?

时间:2016-04-14 14:45:31

标签: sql sql-server sql-server-2008

if object_id( 'tempdb.dbo.#ctp', 'u' ) is not null
  drop table #ctp ;
create table #ctp( id int, mastername varchar( 16 ) ) ;
insert into #ctp values( 1, 'Big Boy' ) ;

if object_id( 'tempdb.dbo.#client', 'u' ) is not null
  drop table #client ;
create table #client( id int, name varchar(16 ), type int ) ;
insert into #client values( 1, 'ABC', 5 ) ;
insert into #client values( 2, 'XYZ', 6 ) ;

if object_id( 'tempdb.dbo.#ctpclient', 'u' ) is not null
  drop table #ctpclient ;
create table #ctpclient( id int, ctpfk int, clientfk int ) ;
insert into #ctpclient values( 1, 1, 1 ) ;
insert into #ctpclient values( 2, 1, 2 ) ;

select   tp.mastername
       , c.name
       , c.type
       , cc.ctpfk
       , cc.clientfk
from     #ctp tp
join     #ctpclient cc
  on     tp.id = cc.ctpfk
join     #client c
  on     c.id = cc.clientfk 
  ;

当前输出

mastername|name|type
Big Boy|ABC|5
Big Boy|XYZ|6

而不是两行输出,我希望输出如下:

mastername|nameone|nametwo
Big Boy   | ABC   | XYZ

这样做的最佳方法是什么,因为我有很多表,比如#ctpclient?

1 个答案:

答案 0 :(得分:0)

假设您总是有2行,则可以使用交叉表(也称为条件聚合)。它看起来像这样。

with SortedValues as
(
    select tp.mastername
        , c.name
        , ROW_NUMBER() over (partition by mastername order by clientfk) as RowNum
    from #ctp tp
    join #ctpclient cc on tp.id = cc.ctpfk
    join #client c on c.id = cc.clientfk
)

select mastername
    , MAX(case when RowNum = 1 then name end) as NameOne
    , MAX(case when RowNum = 2 then name end) as NameTwo
from SortedValues
group by mastername

如果你有不同的数字,你仍然可以完成,但它有点复杂。