可以在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 :(得分:0)
SQL标准表示别名在同一SELECT子句的其他部分中不可见。
计算机科学中的所有问题都可以通过另一层次的间接来解决 - David Wheeler
只需将计算移动到子查询中:
SELECT sumDiv,
sumDiv / dpClose AS divYield
FROM (SELECT (SELECT sum(div)
FROM Dividends
WHERE ...
) AS sumDiv,
...
FROM DailyPrices
...);