簡體   English   中英

如何僅使用SELECT子句(即使用不帶FROM子句的SELECT)創建具有多行和多列的表

[英]How to create table with multiple rows and columns using only SELECT clause (i.e. using SELECT without FROM clause)

我知道在SQL Server中,可以使用不帶FROM子句的SELECT子句,並創建具有一行和一列的表

SELECT 1 AS n;

但是我只是想知道,是否可以使用不帶FROM子句的SELECT子句來創建

  1. 一列多行的表

  2. 具有多列和一行的表

  3. 有多列多行的表

我嘗試了許多組合,例如

SELECT VALUES(1, 2) AS tableName(n, m);

沒有成功。

您可以使用CTE並使用union (如果要顯示重復項,請union all使用union all

所有3種情況的Rextester示例

  • 一列多行

     with tbl1(id) as (select 1 union all select 2) select * from tbl1; 
  • 一排多列

     with tbl2(id,name) as (select 1,'A') select * from tbl2; 
  • 多列多行

     with tbl3(id,name) as (select 1,'A' union all select 2,'B') select * from tbl3; 
-- One column, multiple rows.
select 1 as ColumnName union all select 2; -- Without FROM;
select * from ( values ( 1 ), ( 2 ) ) as Placeholder( ColumnName ); -- With FROM.

-- Multiple columns, one row.
select 1 as TheQuestion, 42 as TheAnswer; -- Without FROM.
select * from ( values ( 1, 42 ) ) as Placeholder( TheQuestion, TheAnswer ); -- With FROM.

-- Multiple columns and multiple rows.
select 1 as TheQuestion, 42 as TheAnswer union all select 1492, 12; -- Without FROM.
select * from ( values ( 1, 2 ), ( 2, 4 ) ) as Placeholder( Column1, Column2 ); -- With FROM.

您可以使用UNION關鍵字完成所有操作

create table tablename as select 1 as n,3 as m union select 2 as n,3 as m

在Oracle中將是雙重的:

create table tablename as select 1 as n,3 as m from dual union select 2 as n,3 as m from dual

您可以使用UNION運算符:

CREATE TABLE AS SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

默認情況下,UNION運算符僅選擇不同的值。 要允許重復值,可以使用UNION ALL。
結果集中的列名通常等於UNION中第一個SELECT語句中的列名。

嘗試這個:

--1) a table with one column and multiple rows
select * into tmptable0 from(
select 'row1col1' as v1
union all
select 'row2col1' as v1
) tmp

--2) a table with multiple columns and one row
select  'row1col1' as v1, 'row1col2' as v2 into tmptable1

--3) a table with multiple columns and multiple rows
select * into tmptable2 from(
select 'row1col1'  as v1, 'row1col2' as v2 
union all
select 'row2col1' as v2, 'row2col2' as v2 
) tmp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM