TSQL,基于非主键和左表的连接表保持不变

时间:2015-06-10 08:39:00

标签: tsql

我该如何查询以获得预期的结果?

Table A
+----+-------+-------------+------------+
+ ID + Model + Description + Material   +
+----+-------+-------------+------------+
+ 1  + M1    + CHASIS      + AC001      +
+ 2  + M1    + SCREW       + AS001      +
+ 3  + M1    + SEAL        + ASE01      +
+ 4  + M1    + SEAL        + ASE02      +
+ 5  + M1    + SEAL        + ASE03      +
+----+-------+-------------+------------+

Table B
+-------+-------------+----------+
+ Model + Description + Material +
+---------+-----------+----------+
+ M2    + CHASIS      + BC001    +
+ M2    + ABS         + BS001    +
+ M2    + SEAL        + BSE01    +
+ M2    + SEAL        + BSE02    +
+-------+-------------+----------+

Expected Result 
+------+--------+---------------+------------+---------+-----------+
+ A.ID + A.Model+ A.Description + A.Material + B.Model + B.Material+
+------+--------+---------------+------------+---------+-----------+
+ 1    + M1     + CHASIS        + AC001      + M2      + BC001     +
+ 2    + M1     + SCREW         + AS001      + NULL    + NULL      +
+ 3    + M1     + SEAL          + ASE01      + M2      + BSE01     +
+ 4    + M1     + SEAL          + ASE02      + M2      + BSE02     +  
+ 5    + M1     + SEAL          + ASE03      + NULL    + NULL      +
+------+--------+---------------+------------+---------+-----------+

我在下面尝试过,但它有SEAL的重复行:

SELECT A.ID, A.model, A.description, A.material,
B.model, B.description, B.material 
FROM A 
LEFT JOIN B 
        ON ( A.Description = B.Description  and B.model = 'M2')
where A.model = 'M1' 

我想基于Description加入两个表格。来自Table A的序列和行应保持不变。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作:

select * from 
(select *,
        row_number() over(partition by Model, Description order by ID) Rn
 from TableA) t1

left join 

(select *,
        row_number() over(partition by Model, Description order by (select null)) Rn
 from TableB) t2 on t1.Rn = t2.Rn and t1.Description = t2.Description and t2.Model = 'M2'