获取列总和并用于计算总计百分比(mySQL) [英] Get column sum and use to calculate percent of total (mySQL)
本文介绍了获取列总和并用于计算总计百分比(mySQL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我桌子上的一个非常基本的外观.我有第1列和第2列,需要生成第3列.第3列只是所有Name
的Number
列的总和除以给定行的Number
.
Here is a very basic look at my table. I have columns 1 and 2 and need to generate column 3. Column 3 is simply the total of the Number
column for all Name
divided by Number
for the given row.
| Name | Number | % of total |
| ------------- |:-------------:| -----: |
| Bob | 5 | 25 |
| Sally | 10 | 50 |
| John | 5 | 25 |
我正在努力获取数字行的总数并将其用作计算余数的值.
I'm struggling with how to get the total of the number row and use this as a value to calculate the rest.
我希望将其作为单个查询而不是两个单独的查询来实现.
I'm looking to do this as a single query instead of two separate if possible.
推荐答案
您只需要CROSS JOIN
Number
列的SUM()
:
SELECT Name, Number, Number * 100 / t.s AS `% of total`
FROM mytable
CROSS JOIN (SELECT SUM(Number) AS s FROM mytable) t
这篇关于获取列总和并用于计算总计百分比(mySQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文