2017-09-06 70 views
0

我已經創建了別名Previousodds列。我想訪問這個列並使用它來返回表的子集。我的查詢是:我如何可以訪問哪些已用CTE創建一個臨時列?

WITH t as 
(SELECT 
    col1, 
    col2, 
    col3, 
    odds, 
    col4 
FROM 
stuff) 

SELECT * 
    , LAG(odds,1,0) OVER (partition by [col1] ORDER BY [col2] AS Previousodds 
FROM t 

-- What I would like to do but can't: 
WHERE (1/Odds - 1/Previousodds) > 0.04 
+2

裹另一個查詢選擇 – Yossi

回答

0

棒,在一個子查詢的SELECT語句:

WITH t as 
(SELECT 
    col1, 
    col2, 
    col3, 
    odds, 
    col4 
FROM 
stuff) 

SELECT * 
FROM 
    (
     SELECT * 
      , LAG(odds,1,0) OVER (partition by [col1] ORDER BY [col2] AS Previousodds 
     FROM t 
    )subquery 
WHERE (1/Odds - 1/Previousodds) > 0.04 

子查詢和熱膨脹係數是一樣的野獸,所以你可以移動即CTE爲這個子查詢的子查詢,或者你可以將這個現在是子查詢的SELECT移入CTE。

+0

從原始表..它在選擇字段 – Yossi

+0

哦,是的!我在那裏看到它。我沒有注意。 – JNevill

+0

@JohnF。 。 。開齋節的答案不僅更簡單,而且避免了一個(潛在的)分零誤差。 –

0

請參閱此。使用第一個CTE創建另一個CTE,以便在實際查詢中實現並使用它們。 JNevill的答案也會起作用。

WITH t as 
(SELECT 
    col1, 
    col2, 
    col3, 
    odds, 
    col4 
FROM 
stuff) 
, 
x as (
SELECT * 
    , LAG(odds,1,0) OVER (partition by [col1] ORDER BY [col2] AS Previousodds 
FROM t)  
SELECT * FROM x 
WHERE (1/Odds - 1/Previousodds) > 0.04 
1

試試這個

WITH t as 
(SELECT 
    col1, 
    col2, 
    col3, 
    odds, 
    col4, 
    LAG(odds) OVER (partition by [col1] ORDER BY [col2] AS Previousodds 

FROM stuff 
) 

SELECT * 
FROM t 
WHERE (1/Odds - 1/Previousodds) > 0.04 
+1

爲了避免被零除錯誤,我會將'lag(賠率,1,0)'改爲'lag(賠率)'。 –

+0

@GordonLinoff你說得對,我編輯過它。 –

相關問題