避免在cte中使用多个联合

时间:2014-03-13 13:00:39

标签: sql-server-2008-r2 where-clause common-table-expression union-all

您好我有一个CTE,其中有5个内部联接,而一个where子句减少了一个。 示例代码如下所示。但实际的代码具有更复杂的逻辑

;With CTE_EG AS
(
 select *,
-1 as offset from a 
 inner join a1 on a1.id=a.id
 inner join a2 on a1.id=a2.id
 inner join a3 on a1.id=a3.id
where a1.offset = a2.quarter-1
union all
 select *,
-2 as offset from a 
 inner join a1 on a1.id=a.id
 inner join a2 on a1.id=a2.id
 inner join a3 on a1.id=a3.id
where a1.offset = a2.quarter-2
union all
   ...
    )

重复到偏移-4和a1.offset = a2.quarter-4。 如何只为一个where子句值避免重复多次相同的代码。实际查询有5个内部联接和总共5个联合。 我无法删除所有联合,因为这会在一些计算中产生差异。 我想要的东西就像我们传递一个整数值n,union之间的选择都应该重复更改where子句,如a1.offset = a2.quarter-2到a1.offset = a2.quarter-n 请建议

1 个答案:

答案 0 :(得分:0)

这应该只是:

;With Numbers(n) as (
  select 1 union all select 2 union all
  select 3 union all select 4
), CTE_EG AS
(
 select *,
-n as offset from a 
 inner join a1 on a1.id=a.id
 inner join a2 on a1.id=a2.id
 inner join a3 on a1.id=a3.id
 inner join numbers n on a1.offset = a2.quarter-n
 )

我不明白你无法移除UNION ALL

的观点