mysql values select,MySQL-如何根据另一个SELECT的值进行SELECT

I have a table that looks something like this:

Name Year Value

A 2000 5

A 2001 3

A 2002 7

A 2003 1

B 2000 6

B 2001 1

B 2002 8

B 2003 2

The user can query based on a range of years, and it will return the sum of Value grouped by Name, as such (assume queried years are 2000 - 2001):

Name SUM(Value)

A 8

B 7

Now, I wanted to insert a calculated field that outputs the ratio of the sum of the values of each name for ALL years to the sum of all values. Basically the percentage of all values attributed to A and B, respectively, like:

Name SUM(Value) % Of Total

A 8 0.484 (16 / 33)

B 7 0.516 (17 / 33)

Note that even though the user queried only 2000-2001, I want the calculation to use the sum across all years. I've been searching and experimenting for hours and I cannot figure out how. I only know how to sum across the queried years like so:

SELECT `Name`, SUM(`Value`)/(SELECT SUM(`Value`) FROM `table1`) AS "% of Total"

FROM `table1`

WHERE `Year` BETWEEN 2000 AND 2001

GROUP BY `Name`;

Please help! I'm very much a novice, and don't understand SQL in much depth, so please clarify any advanced code. Thank you for your kindness.

解决方案

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,

SUM(Value) AS "SUM(VALUE)",

SUM(Value) / totals.total AS "% of Total"

FROM table1,

(

SELECT Name,

SUM(Value) AS total

FROM table1

GROUP BY Name

) AS totals

WHERE table1.Name = totals.Name

AND Year BETWEEN 2000 AND 2001

GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值