Sql 如何使用only SELECT子句(即使用SELECT而不使用FROM子句)创建包含多行和多列的表
我知道在SQLServer中,可以使用SELECT子句而不使用FROM子句,并创建一个包含一行和一列的表Sql 如何使用only SELECT子句(即使用SELECT而不使用FROM子句)创建包含多行和多列的表,sql,sql-server,tsql,Sql,Sql Server,Tsql,我知道在SQLServer中,可以使用SELECT子句而不使用FROM子句,并创建一个包含一行和一列的表 SELECT 1 AS n; 但我只是想知道,是否可以使用SELECT子句而不使用FROM子句来创建 具有一列多行的表 with tbl1(id) as (select 1 union all select 2) select * from tbl1; with tbl3(id,name) as (select 1,'A' union all select 2,'B') select
SELECT 1 AS n;
但我只是想知道,是否可以使用SELECT子句而不使用FROM子句来创建
with tbl1(id) as
(select 1 union all
select 2)
select * from tbl1;
with tbl3(id,name) as
(select 1,'A' union all
select 2,'B')
select * from tbl3;
with tbl1(id) as
(select 1 union all
select 2)
select * from tbl1;
with tbl3(id,name) as
(select 1,'A' union all
select 2,'B')
select * from tbl3;
我试过很多组合,比如
SELECT VALUES(1, 2) AS tableName(n, m);
没有成功。您可以通过使用
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
可以使用联合运算符:
CREATE TABLE AS SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
默认情况下,UNION运算符仅选择不同的值。要允许重复值,可以使用UNION ALL。结果集中的列名通常等于UNION中第一个SELECT语句中的列名。您可以使用CTE并使用
UNION
(如果要显示重复项,请使用UNION all
)
- 一列多行
with tbl1(id) as (select 1 union all select 2) select * from tbl1;
with tbl3(id,name) as (select 1,'A' union all select 2,'B') select * from tbl3;
- 一行多列
with tbl2(id,name) as (select 1,'A') select * from tbl2;
- 多列多行
with tbl1(id) as (select 1 union all select 2) select * from tbl1;
with tbl3(id,name) as (select 1,'A' union all select 2,'B') select * from tbl3;
--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
你想解决的问题是什么?我没有特别的问题。我想我问这些问题是出于好奇。我只是想知道这是否可能,如果可能,如何实现?你能分享一个例子吗?我想知道,在这种情况下,CTE需要什么。谢谢,不用了。如果希望在查询中的多个位置使用同一个表,那么CTE是更好的选择。例如,您可以使用tbl3作为。。。。。选择*from tbl3 a1 internal join tbl3 a2 on…..而不反复写入整个tbl3查询。