2014-03-24 29 views
0

我有一個表其中LOOP

s_hostid | s_name | s_size 
----------+------------+-------------- 
     5 | 2014-01-09 | 1082705867 
     5 | 2014-01-08 | 1082713736 
     5 | 2014-01-04 | 1082686097 
     5 | 2014-01-03 | 1082677818 
     5 | 2014-01-06 | 1082701853 
     10 | 2014-01-06 |  7536036 
     10 | 2014-01-02 |  7536032 
     10 | 2014-01-08 |  7536036 
     10 | 2014-01-01 |  7536020 
     10 | 2014-01-05 |  7536036 
     10 | 2014-01-03 |  7536032 
     10 | 2014-01-09 |  7536032 
     50 | 2014-01-03 | 11416224886 
     11 | 2014-01-01 |   39 
     11 | 2014-01-06 |   39 
     11 | 2014-01-07 |   39 
     11 | 2014-01-09 |   39 
     36 | 2014-01-02 |  22164534 

總和SQL數據如何獲得和值s_size每個值S_NAME場? 我想這

"SELECT s_name,(select sum(s_size) from storage where s_name = (select distinct s_name from storage)) from storage" 

,但有一個錯誤:

ERROR: more than one row returned by a subquery used as an expression 

感謝響應。

+0

你的意思是*沒有*聚合行? –

回答

0

這是group by子句的用途 - 它將查詢分解爲組,並對每個組應用聚合函數。 在你的情況:

SELECT s_name, SUM(s_size) 
FROM  my_table 
GROUP BY s_name 
+0

謝謝!這是我需要的! – Creativie

0

簡單的聚合將是太基本。 The manual answers that all too well.

我假定你正在尋找window functions,即具有求和每個組的所有行返回每一行:

SELECT s_name, sum(s_size) OVER (PARTITION BY s_name) AS group_sum 
FROM tbl; 

在這種情況下,衆所周知的聚合函數sum()作爲後窗函數添加OVER子句。

+0

謝謝,但回答@Mureinik 100%命中。 – Creativie