select x+y as z,
case
when "x"+"y" < 0 then "Less Than Zero"
when "x"+"y" > 0 then "Non Zero"
else "Zero"
end
from sometable;
返回预期结果,但多次对每行数据进行添加。
我正在尝试优化查询,但不能正常工作..
select x+y as z,
case
when "z" < 0 then "Less Than Zero"
when "z" > 0 then "Non Zero"
else "Zero"
end
from sometable;
始终返回&#34;小于零&#34;。
我在这个查询上做错了什么?如何在执行查询时多次避免添加A
和B
?
答案 0 :(得分:0)
SELECT子句中的列别名在同一SELECT子句中的其他表达式中不可用。 (SELECT x AS y, y AS x ...
应该怎么办?)
您可以通过将其移动到子查询来使这样的别名可用:
SELECT z,
CASE WHEN z < 0 THEN 'Less Than Zero'
WHEN z > 0 THEN 'Non Zero'
ELSE 'Zero'
END
FROM (SELECT x + y AS z
FROM sometable);
然而,这只能节省打字;它实际上并没有优化重复计算:
sqlite> explain select z, z from (select x+y as z from sometable); addr opcode p1 p2 p3 p4 p5 comment ---- ------------- ---- ---- ---- ------------- -- ------------- 0 Init 0 11 0 00 Start at 11 1 OpenRead 1 2 0 2 00 root=2 iDb=0; sometable 2 Rewind 1 9 0 00 3 Column 1 0 3 00 r[3]=sometable.x 4 Column 1 1 4 00 r[4]=sometable.y 5 Add 4 3 1 00 r[1]=r[4]+r[3] 6 Add 4 3 2 00 r[2]=r[4]+r[3] 7 ResultRow 1 2 0 00 output=r[1..2] 8 Next 1 3 0 01 9 Close 1 0 0 00 10 Halt 0 0 0 00 11 Transaction 0 0 1 0 01 usesStmtJournal=0 12 TableLock 0 2 0 sometable 00 iDb=0 root=2 write=0 13 Goto 0 1 0 00