使用 Postgres 使用多个 WITH tablename AS (...) 语句

Tit*_*ito 2 sql postgresql common-table-expression postgresql-9.3

对于 SQL 服务器,有一个这样的确切问题,但我使用的是 Postgres 9.3 并且','没有用

我正在比较两个不同的年份。例如 2016 年和 2015 年

我会检查用户在 2 年的课程中是否在相同科目上获得了任何不良成绩。

我的代码如下

with currentyeargrade ( 
      select ....
      from (...
             ...)t)

with previousyeargrade(
      select ....
      from (...
             ...)y)

select *
from currentyeargrade cyg
inner join previousyeargrade pvg on pvg.userid = cyg.userid
Run Code Online (Sandbox Code Playgroud)

我是一名 SQL 开发人员,我没有创建临时表的管理员权限。

D-S*_*hih 6

当你使用CTE 时你只需要写with在第一个CTE并使用,逗号连接多个CTE.

with currentyeargrade as ( 
      select ....
      from (...
             ...)t),
previousyeargrade as(
      select ....
      from (...
             ...)y)
select *
from currentyeargrade cyg
inner join previousyeargrade pvg on pvg.userid = cyg.userid
Run Code Online (Sandbox Code Playgroud)

这是给你的样本

CREATE TABLE T(col int);

insert into T values (1);
Run Code Online (Sandbox Code Playgroud)

查询 1

with currentyeargrade as  (SELECT * FROM T), 
previousyeargrade as (SELECT * FROM T)
select *
from previousyeargrade cyg
CROSS JOIN currentyeargrade pvg 
Run Code Online (Sandbox Code Playgroud)

结果

| col | col |
|-----|-----|
|   1 |   1 |
Run Code Online (Sandbox Code Playgroud)