Sql 选择带有union的列,并将剩余列手动插入表中
我必须根据下面的联合条件从表A中选择ColumnASql 选择带有union的列,并将剩余列手动插入表中,sql,sql-server,Sql,Sql Server,我必须根据下面的联合条件从表A中选择ColumnA TableA => (ColumnA , ColumnB, ColumnC , ColumnD ) 如何编写sql查询,我可以从上面的unionQuery中插入ColumnA,ColumnB、ColumnC、ColumnD应该是硬编码的(例如:a、b、c) 预期产出: Select ColumnA from TableA where ColumnB = 'x' Union Select ColumnA from TableA where
TableA => (ColumnA , ColumnB, ColumnC , ColumnD )
如何编写sql查询,我可以从上面的unionQuery中插入ColumnA,ColumnB、ColumnC、ColumnD应该是硬编码的(例如:a、b、c)
预期产出:
Select ColumnA from TableA where ColumnB = 'x'
Union
Select ColumnA from TableA where ColumnB = 'y'
Output:
ColumnA
123,
456,
789,
543
是否要将这些行插入另一个表中?如果是:
ColumnA , ColumnB, ColumnC , ColumnD
123, a, b, c
456, a, b, c
789, a, b, c
543, a, b, c
还是只想选择那些值
insert into newtable (ColumnA , ColumnB, ColumnC , ColumnD)
select distinct ColumnA, 'a', 'b', 'c' FROM TableA
我想你要找的是:
select distinct ColumnA, 'a' ColumnB, 'b' ColumnC, 'c' ColumnD
FROM TableA
因此,基本上只需编写select查询,因为您已经需要输出所需的所有内容,然后在上面插入正确的列名。只需使用文本值和别名即可
INSERT INTO TableA (ColumnName1, ColumnName 2, ColumnName3, ... )
SELECT ColumnA, 'a', 'b', 'c'
FROM TableA WHERE ...
UNION
Select ColumnB? 'a', 'b', 'c' ...
FROM TABLEB WHERE ....
和用于插入
Select ColumnA, 'b' as columnB, 'c' as ColumnC, 'd' as ColumnD
From TableA where ColumnB = 'x'
Union
Select ColumnA, 'b', 'c', 'd' ColumnD
from TableA where ColumnB = 'y'
insert into TableA (columnA, columnB, columnC, columnD)
Select ColumnA, 'b' as columnB, 'c' as ColumnC, 'd' as ColumnD
From TableA where ColumnB = 'x'
Union
Select ColumnA, 'b', 'c', 'd' ColumnD
from TableA where ColumnB = 'y'