联合查询中的with子句

时间:2018-12-21 11:09:16

标签: sql

我在联合查询中有with子句,例如

with t1 as(...) ---common for both query
select * from t2
union 
select * from t3

在两个查询中如何使用聚类处理?

1 个答案:

答案 0 :(得分:1)

您可以重复使用通用表表达式

例如:

with cte as 
(
  select col1, col2, col3, col4, col5, col6
  from sometable
  where col1 = 42
)
select col1, col2, col3
from cte as t1
union all
select col4, col5, col6
from cte as t2

如果您需要更多的CTE,则可以使用逗号分隔它们。

with cte1 as 
(
  select col1, col2, col3
  from sometable
  where col1 = 42
  group by col1, col2, col3
)
, cte2 as 
(
   select col4, col5, col6
   from sometable
   where col4 > col5
   group by col4, col5, col6
)
select col1, col2, col3
from cte1 as t1
union all
select col4, col5, col6
from cte2 as t2

但是在本示例中,出于美观的原因,将更复杂的查询放在SQL的顶部将更加有用。
因为仅将来自CTE的查询合并在一起会更直接。

select col1, col2, col3
from sometable
where col1 = 42
group by col1, col2, col3

union all

select col4, col5, col6
from sometable
where col4 > col5
group by col4, col5, col6