[英]Sum of values in column by row and also selecting other columns in the result set
我当前的查询如下:
select id, quantity, c, d
from table1;
这将为我提供如下示例数据:
id | quantity | c | d
---------------------
1 | 1 | x | y
1 | 3 | x | y
2 | 1 | x | y
2 | 1 | x | y
但是我想按ID分组并获得数量的总和如下:
id | quantity | c | d
---------------------
1 | 4 | x | y
2 | 2 | x | y
我试图修改我的第一个查询,以在ID上包含一个分组,在数量上包括一个总和:
select id, sum(quantity), c, d
from table1
group by id;
但是我遇到了一个错误,因为其他两列不属于group by子句。 如何包含它们?
简单地将它们添加到group by子句中:
select id, sum(quantity), c, d from table1 group by id, c, d;
在这里使用OVER子句很有意义:
select id, SUM(quantity) OVER (PARTITION BY id), c, d
from table1
不要忘记获得独特的结果。 如果c与d的组合不止一个,则需要明确说明要选择的组合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.