SQL Server:连接表中的重复列,但不同的行信息

时间:2015-03-11 08:59:01

标签: sql-server

所以我加入了两个表来识别索赔及其相应的逆转(如果有的话)。 以下是我所做的简化说明:加入两个表中MbrNo相同的位置,以及Amount = -Amount的位置。所以现在我有一个输出表包含重复的列名:

MbrNo | ClaimType | Amount | MbrNo | ClaimType | Amount
xyz   | Medicine  | R 300  | xyz   | Reversal  | - R300

我不能在表中输入,因为列名不是唯一的。 但我想要 1.将此表格式化为如下所示

MbrNo | ClaimType | Amount 
xyz | Medicine  | R 300 
xyz   | Reversal  | - R300 
with t as 
(   
    select *,
    count(*) over(partition by [MbrNo], [DepNo], [PracticeNo], [DisciplineCd], [ServiceDt],[PayAmt]) as rownum
    from Claims
)
Select * from 
(Select * from t where PayAmt<0) a
left outer join 
(Select * from t where PayAmt>0) b
on a.[MbrNo]=b.[MbrNo]
and a.[DepNo]=b.[DepNo]
and a.[PracticeNo]=b.[PracticeNo]
and a.[DisciplineCd]=b.[DisciplineCd]
and a.[ServiceDt]=b.[ServiceDt]
and a.[PayAmt]=-b.[PayAmt]

基本上我想将第二个表放在第一个表下面的连接表中。

请帮助:(

1 个答案:

答案 0 :(得分:0)

如果我已正确理解您的要求,那么我认为您需要UNION运营商。看看这是否能让你朝着正确的方向前进。

with t as 
(    
    select *,
    count(*) over(partition by [MbrNo], [DepNo], [PracticeNo], [DisciplineCd], [ServiceDt],[PayAmt]) as rownum
    from Claims
)
Select t.* from t where PayAmt < 0
union all
select b.* from
(Select * from t where PayAmt < 0) a
inner join 
(Select * from t where PayAmt > 0) b
on a.[MbrNo] = b.[MbrNo]
and a.[DepNo] = b.[DepNo]
and a.[PracticeNo] = b.[PracticeNo]
and a.[DisciplineCd] = b.[DisciplineCd]
and a.[ServiceDt] = b.[ServiceDt]
and a.[PayAmt] = -b.[PayAmt]