sql从其他表中的列创建表

时间:2017-10-19 03:22:34

标签: sql sql-server

我有4个名为table1,table2,table3,table4的表。每个都有一列分别叫做x,y,z和w:

x               y               z                w
---          ------          ------            ----
1             A               120               Red
2             B                33.3             Orange
3             C                81.3              Green
4             D                 41.3              Blue

我想创建一个新表,只需要它的列,只是这些列的行顺序不变。在R()中,我只会执行类似data.frame(x,y,z,w)的操作,但是,我不知道如何在SQL Server 2016中执行相同的操作。这些表没有公共密钥(除了它们行号当然!)。

1 个答案:

答案 0 :(得分:0)

你可以使用这样的东西:

WITH CTE_Table1 AS (
SELECT x, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS x_row
FROM Table1
), CTE_Table2 AS (
SELECT y, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS y_row
FROM Table2
), CTE_Table3 AS (
SELECT z, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS z_row
FROM Table3
), CTE_Table4 AS (
SELECT w, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS w_row
FROM Table4
)
SELECT x, y, z, w
FROM CTE_Table1
INNER JOIN CTE_Table2 ON CTE_Table1.x_row = CTE_Table2.y_row
INNER JOIN CTE_Table3 ON CTE_Table1.x_row = CTE_Table3.z_row
INNER JOIN CTE_Table4 ON CTE_Table1.x_row = CTE_Table4.w_row