SQL: 根据列A中的分组,对列B进行分组。

huangapple go评论56阅读模式
英文:

SQL: GROUP BY column B for groups in column a

问题

SELECT A, B, SUM(C)
FROM YourTable
GROUP BY A, B
英文:

I am looking for a SQL query that will sum the values in column C GROUP BY column B, but not over the entire table, only within the ranges where the same values are present in column A.

Current table:

Column A Column B Column C
A B 10
A B 5
A B 8
A C 1
A D 7
B B 10
B B 5

Required table:

Column A Column B Column C
A B 23
A C 1
A D 7
B B 15

SELECT A, B, SUM(C)
FROM ...
WHERE ...
GROUP BY B

This obviously doesn't work, because I don't use column A with an aggregate function, nor in the GROUP BY statement. How do I get to the desired solution? Thanks for the help.

答案1

得分: 1

似乎你想按第一列和第二列分组,并求第三列的总和:

SELECT A, B, SUM(C) AS SUM_C,
       100.0 * SUM(C) / SUM(SUM(C)) OVER (PARTITION BY A) AS PCT
FROM yourTable
GROUP BY A, B;
英文:

It seems that you want to group by the first two columns and sum the third:

<!-- language: sql -->

SELECT A, B, SUM(C) AS SUM_C,
       100.0 * SUM(C) / SUM(SUM(C)) OVER (PARTITION BY A) AS PCT
FROM yourTable
GROUP BY A, B;

答案2

得分: -2

你可以进行嵌套分组。订单中的第一列首先对结果进行分组,随后的列在前一组的组内进行分组。

从表中选择计数(*)按A,B分组;
英文:

You can do nested grouping. The first column in the order gets to group the result first and the following columns get grouped within the group of the previous group.

SELECT count(*) FROM table GROUP BY A, B;

huangapple
  • 本文由 发表于 2023年2月8日 17:45:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定