将两个列值插入单个SQL Server

时间:2018-01-29 10:57:29

标签: sql-server

以下两个表格Table 1Table 2 -

Table 1 +-----+------+---------+ | ID | Name | Earning | +-----+------+---------+ | 101 | John | HRA | | 101 | John | Travel | | 102 | Andy | Travel | +-----+------+---------+

Table 2 +-----+------+---------+ | ID | Name |Deduction| +-----+------+---------+ | 101 | John | ENP | | 102 | Andy | ENP | | 102 | Andy | RA | +-----+------+---------+

我需要使用以下列创建第三个表Table 3 我已经创建了两列IDName。我只需要EarningOrDeduction列。

使用

INSERT INTO Table3 (ID, Name, EarningOrDeduction) SELECT ID, Name, Earning FROM Table1 UNION ALL SELECT ID, Name, Deduction FROM Table2;

我正在

Table 3 +-----+------+------------------+ | ID | Name |EarningOrDeduction| +-----+------+------------------+ | 101 | John | HRA | | 101 | John | Travel | | 102 | Andy | Travel | | 101 | John | ENP | | 102 | Andy | ENP | | 102 | Andy | RA | +-----+------+------------------+

但我希望输出为

Table 3 +-----+------+------------------+ | ID | Name |EarningOrDeduction| +-----+------+------------------+ | 101 | John | HRA | | 101 | John | Travel | | 101 | John | ENP | | 102 | Andy | Travel | | 102 | Andy | ENP | | 102 | Andy | RA | +-----+------+------------------+

3 个答案:

答案 0 :(得分:0)

您可以尝试从两个表中插入值的并集:

INSERT INTO Table3 (ID, Name, EarningOrDeduction)
SELECT ID, Name, Earning FROM Table1
UNION ALL
SELECT ID, Name, Deduction FROM Table2;

或者,如果您不想使用这些值填充Table3,则可以在没有第一个插入行的情况下运行上面的选择。

答案 1 :(得分:0)

您可以使用 Union 子句选择两个表格数据。 如果您不想插入已输入的值,请使用以下查询。

INSERT INTO Table3 (EarningOrDeduction)
SELECT X FROM(
SELECT Earning X FROM Table1
UNION
SELECT Deduction X FROM Table2
    ) T
LEFT JOIN Table3 T3 ON T.X=T3.EarningOrDeduction
WHERE T3.EarningOrDeduction IS NULL

答案 2 :(得分:0)

使用Order by的UNION ALL应该可以工作。

INSERT INTO Table3 (ID, Name, EarningOrDeduction)
SELECT ID, Name, EarningOrDeduction from 
(SELECT ID, Name, Earning as [EarningOrDeduction] FROM Table1
UNION ALL
SELECT ID, Name, Deduction FROM Table2) ORDER BY ID, Name;

我认为收益和扣减不会为特定名称产生重复值。