2016-04-25 45 views
0

在SQLite的計算列中可以使用別名嗎?我有以下查詢:SQLite:在計算中使用別名

SELECT 
    dpTicker AS Ticker, 
    max(dpDate) AS Datum, 
    dpClose AS Price, 
    (SELECT 
     sum(div) 
    FROM Dividends 
    WHERE 
     divTicker = DP1.dpTicker 
     AND strftime('%Y', divDate) = strftime('%Y', date('now','-1 Year'))) 
    AS sumDiv, 
    (SELECT 
     sum(div) 
    FROM Dividends 
    WHERE 
     divTicker = DP1.dpTicker 
     AND strftime('%Y', divDate) = strftime('%Y', date('now','-1 Year')))/dpClose*100 
    AS divYield  
FROM DailyPrices AS DP1 
GROUP BY dpTicker 
ORDER BY divYield DESC; 

正如你可以在上面查詢發現,對於sumDiv代碼重複兩次。我一直在尋找如何在計算列中使用別名,但是,我的嘗試是不成熟的。

在計算中直接使用別名(sumDiv)會導致錯誤消息。我已閱讀,卷繞在SELECT語句的別名應該工作:

(SELECT sumDiv)/dpClose AS divYield 

在相同的錯誤這種嘗試的結果:

bash-3.2$ sqlite3 myShares < Queries/test.sql 
Error: near line 1: no such column: sumDiv 

可以別名在計算中使用,還是我必須重複代碼兩次?

在此先感謝您的任何反饋意見,並幫助抓取SQLite學習曲線。

最好的問候,

GAM

回答

0

SQL標準說,別名不是在同一個SELECT子句的其他部分可見。

All problems in computer science can be solved by another level of indirection.
— David Wheeler

只是移動計算爲子查詢:

SELECT sumDiv, 
     sumDiv/dpClose AS divYield 
FROM (SELECT (SELECT sum(div) 
       FROM Dividends 
       WHERE ... 
      ) AS sumDiv, 
      ... 
     FROM DailyPrices 
     ...);