2016-01-14 54 views
0

我想要选择值,执行一些计算,例如乘以两列,然后在列值相同的位置添加它们。举例来说,如果我有这样一个表如下:在存在公共列值的情况下执行计算

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语句中做到这一点?

+0

http://sqlfiddle.com/#!9/07290/8 – Gayathri

回答

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 
相关问题