在存在常见列值的情况下执行计算

时间:2016-01-14 15:36:49

标签: mysql sql

我想选择值,执行一些计算,假设将两列相乘,然后将其添加到其中一列值相同的位置。例如,如果我有一个如下表:

id     prm
1      12
3      14
1      13
2      20
1      17
3      11

我想首先将id和prm相乘,然后在有共同id的地方添加它们,这样就会添加第1行,第3行和第5行,并添加第2行和第6行。然后我希望输出按id的降序排列。最终的出局看起来像:

75 40 42

因为3 * 14 + 3 * 11 = 75,2 * 20 = 40,并且1 * 12 + 1 * 13 + 1 * 17 = 42。 我希望我的问题很明确。 有没有办法在一个sql语句中执行此操作?

2 个答案:

答案 0 :(得分:1)

select id, sum(id*prm)
from tablename
group by id order by 2 desc

检查此 - >如果符合您的要求,则http://sqlfiddle.com/#!9/07290/8

答案 1 :(得分:0)

您可以group by ID。

select id, sum(id*prm)
from yourtable
group by id

要将结果放在一行,您可以

select 
max(case when id = 1 then `total` end) as id1,
max(case when id = 2 then `total` end) as id2,
max(case when id = 3 then `total` end) as id3
from (
select id, sum(id*prm) as `total`
from yourtable
group by id) t
相关问题