如何根据列值进行特定的MySQL计算?

时间:2013-02-05 23:46:24

标签: mysql math

有没有办法将列与基于另一列的预定义数相乘?根据列中的值,使用多个预定义数字。

示例:

Columns: persons_id,activity,scale 

1,swimming,4  
1,baseball,2  
1,basketball,3  
2,swimming,6  
2,basketball,3

如果我的预定义数字是:6(游泳),8(棒球),5(篮球)

输出看起来像这样

1,swimming,4,24  
1,baseball,2,16  
1,basketball,2,10  
2,swimming,6,36  
2,basketball,3,15

编辑:谢谢大家的贡献。我最终使用了sgeddes的解决方案。

4 个答案:

答案 0 :(得分:4)

当然,您可以使用CASE

SELECT Persons_Id, Activity, Scale, 
   Scale * 
   CASE 
      WHEN Activity = 'swimming' THEN 6
      WHEN Activity = 'baseball' THEN 8
      WHEN Activity = 'basketball' THEN 5
      ELSE 1
   END Total
FROM YourTable
祝你好运。

答案 1 :(得分:0)

让另一个名为WEIGHT的列加倍SCALE值。也许您可以使用触发器来填充列来计算产品。否则,一个简单的SELECT就可以了。

答案 2 :(得分:0)

您可以使用此查询:

select persons_id, activity, scale, 
 scale * case when activity = 'swimming' then 6
              when activity = 'baseball' then 8
              when activity = 'basketball' then 5 end as result
from Table1

但更好的解决方案是定义一个新表Coefficients(activity,coefficient)

以便您可以插入行: '游泳',6 '棒球',8 '篮球',5

然后使用这样的东西:

select persons_id, activity, scale, scale * coefficient as result
from Table1 inner join Coefficients on Table1.activity = Coefficients.activity

答案 3 :(得分:0)

您还可以使用存储值的表或创建将返回乘数的子查询:

select persons_id,
  t.activity,
  scale, 
  scale * s.val  as result
from yourtable t
inner join
(
  select 'swimming' activity, 6 val
  union all
  select 'baseball' activity, 8 val
  union all
  select 'basketball' activity, 5 val
) s
  on t.activity = s.activity

请参阅SQL Fiddle with Demo

结果是:

| PERSONS_ID |   ACTIVITY | SCALE | RESULT |
--------------------------------------------
|          1 |   swimming |     4 |     24 |
|          1 |   baseball |     2 |     16 |
|          1 | basketball |     3 |     15 |
|          2 |   swimming |     6 |     36 |
|          2 | basketball |     3 |     15 |