使用 CTE 在 SQL 中生成测试数据

Use CTE to generate test data in SQL

我正在尝试使用 CTE 为 SQL (postgresql) 中的单元测试生成数据 table。

WITH temp1 AS (
SELECT
  ('A', 'A', 'B', 'B') AS grp,
  (1, 2, NULL, 1) AS outcome
)

SELECT * 
FROM temp1

上面的查询生成单行而不是 4 行 table,这对我的单元测试很有用。如何以以下形式生成 4 行 table:

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

Demo on DB Fiddle:

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