gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:06:53 31 4
gpt4 key购买 nike

我有这张表:

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

最佳答案

这是 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 |

关于sql - 如何添加一列,如另一列的 sum(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31776403/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com