0

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

例子:

桌子

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

4 回答 4

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

祝你好运。

于 2013-02-05T23:49:22.300 回答
0

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

于 2013-02-05T23:49:15.457 回答
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)

这样您就可以插入行:'swimming', 6 'baseball', 8 'basketball', 5

然后使用这样的东西:

select persons_id, activity, scale, scale * coefficient as result
from Table1 inner join Coefficients on Table1.activity = Coefficients.activity
于 2013-02-05T23:51:55.013 回答
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

结果是:

| 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 |
于 2013-02-05T23:53:28.000 回答