2015-11-04 111 views
1

我需要根據其他操作結果進行操作。例如:基於其他操作結果的MySQL查詢操作

SELECT 
    SUM(first_column) as res1, 
    SUM(second_column) as res2, 
    res1/res2 as res3 
FROM my_table 

但是,它似乎只能對現有列進行操作。這個用例的解決方法是什麼?

+0

那麼你可以說結果集..和整個查詢 –

回答

2

您可以使用子查詢來實現這一目標。 事情是這樣的:

SELECT res1, res2, res1/res2 as res3 
(SELECT SUM(xxx) as res1, SUM(xxx) as res2 
FROM yyy) as subquery 
+0

謝謝,這正是我在尋找! – jeanmonod

1

嘗試類似:

SELECT res1/res2 as res3 
FROM (SELECT SUM(xxx) as res1, SUM(xxx) as res2 
     FROM yyy)) 
1
SELECT res1/res2 as res3 
FROM (SELECT SUM(xxx) as res1, SUM(xxx) as res2 
FROM yyy)) 

這應該工作

1

您可以使用您的問題這段代碼塊:

select t.res1 
    ,t.res2 
    ,t.res1/t.res2 as res3 
from (select sum(xxx) as res1 
      ,sum(xxx) as res2 
     from yyy) t 

OR

不推薦,但作品。

select sum(xxx1) as res1 
    ,sum(xxx2) as res2 
    ,sum(xxx1)/sum(xxx2) as res3 
    from yyy 
0

如果您不需要的中間結果,你可以跳過子查詢獲得更好的性能:

SELECT SUM(c1)/SUM(c2) AS res FROM t 
+0

是的,但我需要三個結果... – jeanmonod