表格中的两行变成单行

时间:2019-08-29 05:07:43

标签: sql-server

Type            TableName       TableRowCount  
Source          table_1         1
Destination     table_1         3
Source          table_2         10
Destination     table_2         5

SourceTableName  SourceTableRowCount     DestinationTableName  DestinationTableRowCount
--------------  -------------------      --------------------   ------------------------
table_1             1                       table_1                 3
table_2             10                      table_2                 5

2 个答案:

答案 0 :(得分:0)

这是您的查询。

select t1.TableName As SourceTableName, t1.SourceTableRowCount as SrcCnt, t2.TableName as DestinationTableName, t2.TableRowCount as DestinationTableRowCount from test t1
left join test t2 on t2.Type != t1.Type and t2.TableName = t1.TableName 
where t2.Type = 'Destination'

答案 1 :(得分:0)

您可以使用inner join获得所需的结果。首先,根据需要在不同的记录集中过滤结果,然后根据基本值(在这种情况下为tablename)的联接将它们组合起来。

; with cte as (
select TableName as SourceTableName, TableRowCount as SourceTableRowCount from yourtable 
where type = 'source'
)
, ct as (
select TableName as DestinationTableName, TableRowCount as DestinationTableRowCount from yourtable 
where type = 'Destination'
)
select * from cte inner join ct on cte.SourceTableName = ct.DestinationTableName