Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择带有union的列,并将剩余列手动插入表中_Sql_Sql Server - Fatal编程技术网

Sql 选择带有union的列,并将剩余列手动插入表中

Sql 选择带有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

我必须根据下面的联合条件从表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 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'