我有一张表Test,它的数据是:
A B
1 One
2 One
2 Two
3 One
2 One
5 Two
2 Three
2 Two
2 Three
2 Two
2 One
现在我想要输出如下:
A B
10 One
10 One
11 Two
10 One
10 One
11 Two
4 Three
11 Two
4 Three
11 Two
10 One
我试过
SELECT B,SUM(A)FROM Test GROUP BY A但是我得到了:
One 10
Three 4
Two 11
任何人都可以告诉我如何以最短的方式实现同样的目标,提前谢谢。
答案 0 :(得分:4)
SELECT SUM(A) OVER (PARTITION BY B), B FROM Test
答案 1 :(得分:1)
select t1.B, t2.sum_a
FROM Test t1
join (select b, sum(a) as sum_a from test group by b) t2 on t1.b = t2.b
答案 2 :(得分:0)
我会尝试创建一个子选择,其中包含总和和B列的组,然后将此子选择与当前表连接。
SELECT original.B, subquery.total
FROM original
INNER JOIN (
SELECT B, SUM(A) AS total FROM original GROUP BY B) as subselect ON original.B = subquery.B
检查此其他stackoverflow:How to write subquery inside the OUTER JOIN Statement