0

您好我有一個CTE有5個內部聯接和一個where子句減少一個。 示例代碼如下所示。但實際的代碼有更復雜的邏輯避免多重聯合所有在cte

;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 請建議

回答

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點。