所以只需使用GROUP BY
像這樣:
SELECT SUM(ACQUISITIONPRICE) AS TOTALPRICE
, EXTRACT(year from DATEACQUIRED) AS YEAR
FROM TRANS
GROUP BY EXTRACT(year from DATEACQUIRED)
ORDER BY YEAR
如果你真的想在一排「加入」所有這些,有具體列名,您可以執行以下操作(儘管此方法不太靈活,因爲每年都必須手動修改查詢)。 還要注意,雖然問題明確提到了「加入」結果,但下面所示的加入完全沒有必要。每列可以簡單地成爲沒有任何連接的select子句的一部分。 (here is the SqlFiddle)
SELECT * FROM
(SELECT SUM(ACQUISITIONPRICE) AS YEAR_2007
FROM TRANS
WHERE EXTRACT(year from DATEACQUIRED) = 2007) a
JOIN
(SELECT SUM(ACQUISITIONPRICE) AS YEAR_2008
FROM TRANS
WHERE EXTRACT(year from DATEACQUIRED) = 2008) b ON 1=1
JOIN
(SELECT SUM(ACQUISITIONPRICE) AS YEAR_2009
FROM TRANS
WHERE EXTRACT(year from DATEACQUIRED) = 2009) c ON 1=1
如果你想在一個單列的結果,一個最好的方法是使用一個子選擇與dual
如圖this fiddle:
SELECT
(SELECT SUM(ACQUISITIONPRICE) FROM TRANS WHERE EXTRACT(year from DATEACQUIRED) = 2007) AS YEAR_2007
, (SELECT SUM(ACQUISITIONPRICE) FROM TRANS WHERE EXTRACT(year from DATEACQUIRED) = 2008) AS YEAR_2008
, (SELECT SUM(ACQUISITIONPRICE) FROM TRANS WHERE EXTRACT(year from DATEACQUIRED) = 2009) AS YEAR_2009
FROM dual
當涉及到性能,唯一真正可以肯定的方法是在特定情況下測試它,但the SUM (CASE...
approach shown by @Indra-Prakash-Tiwari在大多數情況下可能表現更好(if oracle behaves anything like sql server)
非常感謝你。 – CJM