使用CTE在SQL中生成测试数据
我正在尝试使用CTE为SQL(postgresql)中的单元测试生成数据表 上面的查询生成的是一个单行表,而不是对我的单元测试有用的4行表。如何以以下形式生成4行表:使用CTE在SQL中生成测试数据,sql,postgresql,select,common-table-expression,Sql,Postgresql,Select,Common Table Expression,我正在尝试使用CTE为SQL(postgresql)中的单元测试生成数据表 上面的查询生成的是一个单行表,而不是对我的单元测试有用的4行表。如何以以下形式生成4行表: grp.....outcome A.......1 A.......2 B.......NULL B.......1 你不需要CTE。使用UNION ALL,如中所示: select 'A' as grp, 1 as outcome union all select 'A', 2 union all select 'B', nu
grp.....outcome
A.......1
A.......2
B.......NULL
B.......1
你不需要CTE。使用
UNION ALL
,如中所示:
select 'A' as grp, 1 as outcome
union all select 'A', 2
union all select 'B', null
union all select 'B', 1
您可以使用
values()
语法创建行,如下所示:
with temp1(grp, outcome) as (values ('A', 1), ('A', 2), ('B', null), ('B', 1))
select * from temp1
:
grp | outcome
:-- | ------:
A | 1
A | 2
B | null
B | 1
grp |结果
:-- | ------:
A | 1
A | 2
B |空
B | 1
在CTE内部使用
UNION
。
grp | outcome
:-- | ------:
A | 1
A | 2
B | null
B | 1
WITH temp1 AS (
SELECT 'A' as grp ,1 as outcome
UNION
SELECT 'A', 2
UNION
SELECT 'B',NULL
UNION
SELECT 'B',1
) SELECT * FROM temp1