创建列对同一视图中另一列的值求和

时间:2017-06-23 15:16:17

标签: sql sql-server

sample2 = pd.DataFrame({'X': [1,2,3,1,2,3,1,2,1,2,3],
                        'Y': [1,1,1,2,2,2,3,3,4,4,4],
                        'G': [0,0,0,1,1,1,2,2,3,3,3]})

colors = cm.rainbow(np.linspace(0, 1, 4))
for name, group in sample2.groupby(['G']):
    plt.plot(group['X'], group['Y'], c=colors[name])
plt.show()

我需要根据B列对A列中的值求和。因此,B列中值为1的所有值都从A列中提取值,然后将其与C列相加。

2 个答案:

答案 0 :(得分:0)

您可以像这样使用SUM() OVER

DECLARE @SampleData AS TABLE
(
    A int,
    B int
)

INSERT INTO @SampleData
(
    A,
    B
)
VALUES
( 10, 1),
( 15, 2),
( 12, 3),
( 5 , 2),
( 2 , 1),
( 2 , 1)

SELECT *,
       sum(sd.A) OVER(PARTITION BY sd.B) AS C
FROM @SampleData sd

返回

A   B   C
-----------
10  1   14
2   1   14
2   1   14
15  2   20
5   2   20
12  3   12

答案 1 :(得分:0)

我不明白这一点,但是:

SELECT t.a
    ,t.b
    ,sumtab.c
FROM [yourtable] t
INNER JOIN (
    SELECT t.b
        ,sum(t.a) AS C
    FROM [yourtable] t
    GROUP BY t.b

    ) AS sumtab
    ON t.b = sumtab.b