SQL - 组合不同数量的值的列

时间:2016-10-06 16:35:43

标签: sql sql-server

我有3张表中包含不同数据的表。具体而言,每个表中每个mainID的值的数量不同。我想做的是编写一个查询,从3个表中获取信息并将其转换为底部的“最终表”。

表1

mainID      value
------      ------
ID1         Dogs
ID1         Cats
ID1         Elephant
ID1         Snake
ID1         Tiger
ID1         Lamb
ID2         Dogs
ID2         Cats
ID2         Elephant
ID2         Snake
ID2         Tiger
ID2         Lamb

表2

mainID      value
------      ------
ID1         Pencil
ID2         Pencil

表3

mainID      value
------      ------
ID1         Milkshake
ID1         Kool-Aid
ID2         Water
ID2         Soda

决赛桌

mainID      Table1Value       Table2Value        Table3Value
------      -----------       -----------        -----------
ID1         Dogs              Pencil             Milkshake
ID1         Cats                                 Kool-Aid
ID1         Elephant
ID1         Snake
ID1         Tiger
ID1         Lamb
ID2         Dogs              Pencil             Water
ID2         Cats                                 Soda
ID2         Elephant
ID2         Snake
ID2         Tiger

谢谢

1 个答案:

答案 0 :(得分:0)

您需要Left Join table2table3 table1

这样的事可以帮到你

;WITH tab1
     AS (SELECT Row_number()OVER(partition BY [mainID] ORDER BY [value]) rn,*
         FROM   Table1),
     tab2
     AS (SELECT Row_number()OVER(partition BY [mainID] ORDER BY [value]) rn,*
         FROM   Table2),
     tab3
     AS (SELECT Row_number()OVER(partition BY [mainID] ORDER BY [value]) rn,*
         FROM   Table3)
SELECT a.mainID,
       a.value AS Table1Value,
       b.value AS Table2Value,
       c.value AS Table3Value
FROM   tab1 a
       LEFT JOIN tab2 b
              ON a.rn = b.rn
                 AND a.mainID = b.mainID
       LEFT JOIN tab3 c
              ON a.rn = c.rn
                 AND a.mainID = c.mainID 

注意:结果顺序没有列,因此结果顺序可能略有不同。如果您有任何要订购的列,请将结果添加到ROW_NUMBER窗口函数Order by