SQL 中的 Cte 中的 Cte

Cte within Cte in SQL

我遇到过这样一种情况,我需要在 CTE 中对 CTE 的结果应用 where, group by 条件。

Table1如下

+---+---+---+---+
| x | y | z | w |
+---+---+---+---+
| 1 | 2 | 3 | 1 |
| 2 | 3 | 4 | 2 |
| 3 | 2 | 5 | 3 |
| 1 | 2 | 6 | 2 |
+---+---+---+---+

Table 2个如下

+---+---+-----+---+
| a | b |  c  | d |
+---+---+-----+---+
| 1 | m | 100 | 1 |
| 2 | n |  23 | 2 |
| 4 | o |  34 | 4 |
| 1 | m |  23 | 2 |
+---+---+-----+---+

假设我在名为 TAB

的 table 中有以下 sql 查询的数据
with cte as (
select x,y,z from table1),
cte1 as (select a,b,c from table2)
select cte.x,cte1.y,cte1.z,cte2.b,cte2.c from cte left join cte1 on cte.x=cte.a and cte1.w=cte2.d

以上CTE的结果如下

+---+---+---+---+---+-----+
| x | y | z | w | b |  c  |
+---+---+---+---+---+-----+
| 1 | 2 | 3 | 1 | m | 100 |
| 2 | 3 | 4 | 2 | n |  23 |
| 1 | 2 | 6 | 2 | m |  23 |
+---+---+---+---+---+-----+

我想从 table TAB
中查询以下内容
select * from TAB where (X||b) in (select (X||b) from TAB group by (X||Y) having sum(c)=123)

我正在尝试按如下方式制定 SQL 查询,但它并不像我预期的那样:
select * from (

with cte as (
select x,y,z from table1),
cte1 as (select a,b,c from table2)
select cte.x,cte1.y,cte1.z,cte2.b,cte2.c from cte left join cte1 on cte.x=cte.a) as TAB 

where ((X||b) in (select (X||b) from TAB group by (X||Y) having sum(c)=123))

最后的结果一定是这样

+---+---+---+---+---+-----+
| x | y | z | w | b |  c  |
+---+---+---+---+---+-----+
| 1 | 2 | 3 | 1 | m | 100 |
| 1 | 2 | 6 | 2 | m |  23 |
+---+---+---+---+---+-----+

我认为 DB2 不允许子查询中的 CTE 或嵌套。为什么不使用另一个 CTE 来编写这个?

with cte as (
      select x,y,z from
      table1
     ),
     cte1 as (
      select a,b,c
      from table2
     ),
     tab as (
      select cte.x,cte1.y,cte1.z,cte1.w,cte2.b,cte2.c
      from cte left join
           cte1
           on cte.x=cte.a and cte1.w=cte2.d
     )
select *
from TAB
where (X||b) in (select (X||b) from TAB group by (X||Y) having sum(c)=123);