2009-10-08 111 views
5

假設我有這張表SELECT SUM as field

表(a,b,c,d)。數據類型不重要。

我想這樣做

select a as a1,b as b1,c as c1, 
     (select sum(d) from table where a=a1 and b=b1) as total 
from table 
group by a,b,c 

...但我不能找到一種方法(「FROM子句中未找到」的SQLDeveloper保持與抱怨。)

有沒有辦法?可能嗎?

+0

謝謝你們。我得到的東西比我想要的要多得多,並且知道我會閱讀有關分區和分區的內容。這是我喜歡的。 – Tom 2009-10-08 15:38:25

+0

多數民衆贊成在「現在我會讀...」 – Tom 2009-10-08 15:54:38

回答

8
SELECT a as a1,b as b1,c as c1, 
     (
     SELECT SUM(d) 
     FROM mytable mi 
     WHERE mi.a = mo.a 
       AND mi.b= mo.b 
     ) as total 
FROM mytable 
GROUP BY 
     a, b, c 

它更簡單,高效重寫它作爲這樣的:

SELECT a AS a1, B AS b1, c AS c1, SUM(SUM(d)) OVER (PARTITION BY a, b) AS total 
FROM mytable 
GROUP BY 
     a, b, 

注意SUM(SUM(d))這裏。

最內層的SUM是聚合函數。它會計算SUM(d)a-b-c -wise。

最外層的SUM是分析函數。它將預先計算的SUM(d)a-b相加,然後返回每一行的值。

2

杜你的意思是這樣的?

select a as a1, 
     b as b1, 
     c as c1, 
     sum(sum(d)) OVER (PARTITION BY a, b) AS total 
from table 
group by a,b,c 
+0

「OVER(分區由a,b)」買你?沒有聲明的這一部分,這是否行不通? – Jay 2009-10-08 15:12:18

+0

否。與PARTITION BY結合使用的OVER子句將結果集分割爲多個分區,然後將聚合函數應用於此分區。有關更多信息,請閱讀http://msdn.microsoft.com/en-us/library/ms189461.aspx。 – 2009-10-08 15:14:08

+0

您需要一個'SUM(SUM(d))'這裏。 – Quassnoi 2009-10-08 15:15:19

1

你可以用別名做到這一點:

SELECT a AS a1, b AS b1, c AS c1, 
     (SELECT SUM(d) 
      FROM test_t t_in 
      WHERE t_in.a = t.a 
      AND t_in.b = t.b) AS total 
    FROM test_t t 
GROUP BY a, b, c