英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论