我不确切地知道如何说出这个问题但在这里。 我想重用我在查询中计算的值来计算另一个值。 变量是我猜的正确的单词。这是我的疑问:
SELECT
t1.label as label,SUM(t1.totalEvents) as Entry,SUM(t2.totalEvents) as Back,
ROUND(Entry/Back*100,2) as 'Rate'
FROM
trackReports_daily t1
.... rest of query ...
内部回合我想使用SUM返回的值(t1.totalEvents),但当我使用Entry
时,我收到此错误Unknown column 'Entry' in 'field list'
如果没有像这样重新计算,我怎么能在那里获得价值:
ROUND(SUM(t2.totalEvents)/SUM(t1.totalEvents)*100,2)
答案 0 :(得分:10)
看一下这个例子
select (select @t1:=sum(field1)),(select @t2:=sum(field2)),@t1/@t2 from table
答案 1 :(得分:5)
您可以使用子查询:
SELECT label, Entry, Back, ROUND(Entry/Back*100,2) as 'Rate'
FROM (
SELECT SUM(t1.totalEvents) as Entry, SUM(t2.totalEvents) as Back, t1.label as label
FROM trackReports_daily t1
.... rest of query ...
) as temp;
答案 2 :(得分:1)
一种选择是在FROM子句中使用子查询,如:
SELECT
t1.label as label,SUM(t1.totalEvents) as Entry,t2.Back,
ROUND(t1.Entry/t2.Back*100,2) as 'Rate'
FROM
(SELECT *, SUM(totalEvents) as Entry FROM trackReports_daily) t1
(SELECT *, SUM(totalEvents) as Back FROM someTable) t2
.... rest of query ...
如果你想在进一步的查询中重用Rate,那么它会变得复杂,我不知道这是否会有最佳性能,但我认为它会做你在你的例子中所要求的。