从两个表连接时如何将select设置为null或什么都没有?

时间:2018-05-04 04:27:44

标签: sql-server

这是我的第一个表1:

ID | Name1 | Name2 | Name3
---+-------+-------+------
1  |  aaa  |  bbb  |  ccc
2  |  aab  |  bbc  |  cca
3  |  abb  |  bcc  |  caa

这是我的另一个表2:

t1ID | NameT1
-----+-------
1    |  eee
1    |  fff
1    |  ggg
2    |  hhh
3    |  iii
3    |  jjj

我想像这样加入两个表

ID | Name1 | Name2 | Name3 | NameT1
---+-------+-------+-------+--------
1  |  aaa  |  bbb  |  ccc  |  eee
1  |       |       |       |  fff
1  |       |       |       |  ggg
2  |  aab  |  bbc  |  cca  |  hhh
3  |  abb  |  bcc  |  caa  |  iii
3  |       |       |       |  jjj

我尝试使用INNER JOINUNION ALL,但是它给了我这个结果

ID | Name1 | Name2 | Name3 | NameT1
---+-------+-------+-------+--------
1  |  aaa  |  bbb  |  ccc  |  eee
1  |  aaa  |  bbb  |  ccc  |  fff
1  |  aaa  |  bbb  |  ccc  |  ggg
2  |  aab  |  bbc  |  cca  |  hhh
3  |  abb  |  bcc  |  caa  |  iii
3  |  abb  |  bcc  |  caa  |  jjj

那么,对此有何建议?

2 个答案:

答案 0 :(得分:2)

试试这个

;WITH CTE
AS
(
    SELECT
      RN = ROW_NUMBER() OVER(PARTITION BY T1.[ID] ORDER BY T1.[ID]),
      ID = T1.[ID],
      T1.Name1,
      T1.Name2,
      T1.Name3,
      T2.NameT1
      FROM T1
        INNER JOIN T2
            ON T1.ID = T2.t1ID
)
SELECT
  ID,
  Name1 = CASE RN WHEN 1 THEN Name1 END,
  Name2 = CASE RN WHEN 1 THEN Name2 END,
  Name3 = CASE RN WHEN 1 THEN Name3 END,
  NameT1
  FROM CTE

请找到SQL Fiddle Here

http://sqlfiddle.com/#!18/305ec/4

答案 1 :(得分:2)

尝试:您可以使用CTE和窗口功能实现此结果,如下所示:

CREATE TABLE #tableA(ID INT, Name1 VARCHAR(50), Name2 VARCHAR(50), Name3 VARCHAR(50))
INSERT INTO #tableA VALUES
(1,'aaa','bbb','ccc'),
(2,'aab','bbc','cca'),
(3,'abb','bcc','caa')

CREATE TABLE #tableB(t1ID INT, NameT1 VARCHAR(50))
INSERT INTO #tableB VALUES
(1,'eee'),
(1,'fff'),
(1,'ggg'),
(2,'hhh'),
(3,'iii'),
(3,'jjj')

;WITH tabB AS (
    SELECT *,
        RANK() OVER(PARTITION BY t1ID ORDER BY NameT1) rnk
    FROM #tableB B),

    tabA AS (
    SELECT *,
        RANK() OVER(PARTITION BY ID ORDER BY Name1) rnk
    FROM #tableA A)

SELECT B.t1ID, 
    ISNULL(A.Name1, '') AS Name1, 
    ISNULL(A.Name2, '') AS Name2, 
    ISNULL(A.Name3, '') AS Name3, 
    B.NameT1
FROM tabB B
LEFT JOIN tabA A ON A.rnk = B.rnk AND A.ID = B.t1ID
ORDER BY B.t1ID

<强>输出:

t1ID    Name1   Name2   Name3   NameT1
1       aaa     bbb     ccc     eee
1                               fff
1                               ggg
2       aab     bbc     cca     hhh
3       abb     bcc     caa     iii
3                               jjj