如何添加列,如另一列的sum()

时间:2015-08-02 20:45:15

标签: sql postgresql

我有这张桌子:

id|Type | Value
--------------
1 |Type1|Value1
2 |Type1|Value2
3 |Type1|Value3
4 |Type2|Value4

我希望得到另一列,其值等于相同类型Type列的值的sum()。 像那样:

id|Type | Value | Total
-----------------------
1 |Type1|Value1 |Value1+Value2+Value3
2 |Type1|Value2 |Value1+Value2+Value3
3 |Type1|Value3 |Value1+Value2+Value3
4 |Type2|Value4 |Value4

2 个答案:

答案 0 :(得分:4)

这是window functions的一个很好的用例。使用sum() over (partition by ...)

select id, type, value, sum(value) over (partition by type)
from table1;

Sample SQL Fiddle

示例数据:

| id |  type | value |
|----|-------|-------|
|  1 | Type1 |     1 |
|  2 | Type1 |     2 |
|  3 | Type1 |     3 |
|  4 | Type2 |     4 |

给出样本结果:

| id |  type | value | sum |
|----|-------|-------|-----|
|  1 | Type1 |     1 |   6 |
|  2 | Type1 |     2 |   6 |
|  3 | Type1 |     3 |   6 |
|  4 | Type2 |     4 |   4 |

答案 1 :(得分:1)

您可以为此目的使用GROUP BY子句,如

select t1.id, t1.Type, t1.Value, xxx.Total
from table1 t1 join
(
select Type, sum(Value) as Total
from table1
group by Type
) xxx on t1.Type = xxx.Type;