[英]Sum all like columns with the column name as one column, and the total in the other
I have a table with some data similar to this: 我有一张桌子,上面有一些类似的数据:
col1 | col2
-----------
val1 1
val1 5
val1 7
val2 3
val2 1
val2 4
val3 8
What I would like is a query to produce something like this: 我想要的是产生这样的查询:
col1 | sum
----------
val1 13
val2 8
val3 8
I've tried doing this with complicated subqueries, but nothing is quite panning out. 我已经尝试过使用复杂的子查询来执行此操作,但是并没有解决任何问题。 I think I may be overthinking it. 我想我可能会想得太多。
This should be all you need. 这应该是您所需要的。 This uses the aggregate SUM
with a GROUP BY
. 这将合计SUM
与GROUP BY
。
SELECT col1, SUM(col2)
FROM unicorns
GROUP BY col1
select col1, sum(col2) as sum from table group by col1
You just need to use the aggregate function sum()
with a group by
: 您只需要将聚合函数sum()
与group by
:
select col1, SUM(col2) total
from yourtable
group by col1
Select col1, Sum(col2) sum
From table
Group By col1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.