根据SQL Server中的其他列值计算列

时间:2016-07-14 02:28:27

标签: sql sql-server

$products = $this->get('doctrine')->getRepository('YourBundle:Product')->getAllProductsWithFeatures(); select语句的结果如下所示:

sql

我想在上面的结果中添加一个列 - select * from table Location Role Days ----------------------------------- Hong Kong Senior Associate 48 Canberra Senior Associate 60 Sydney Senior Associate 55 (SQL Server表中没有小时列)。

Hours应根据位置

进行计算
  • 如果是香港,那么Days / 7
  • 如果是堪培拉,那么Days / 7.5
  • 如果悉尼然后是Days / 7.25

结果应该是:

Hours

我尝试使用Location Role Days Hours ----------------------------------------- Hong Kong Senior Associate 48 6.85 Canberra Senior Associate 60 8 Sydney Senior Associate 55 7.586 ,它只检查一个条件(if和else)和列应该在数据库中。

select case

但是我想要在一个SQL语句中检查所有条件并添加不在数据库中的小时列。

请提出任何建议。

2 个答案:

答案 0 :(得分:5)

case解决了这个问题:

select location, role, days,
       (case when location = 'Hong Kong' then days / 7.0
             when location = 'Canberra' then days / 7.5
             when location = 'Sydney' then days / 7.25
        end) as hours
from t;

您甚至可以使用计算列将此列添加到表中:

alter table t
    add hours as (case when location = 'Hong Kong' then days / 7.0
                       when location = 'Canberra' then days / 7.5
                       when location = 'Sydney' then days / 7.25
                  end);

答案 1 :(得分:1)

在你查询中:

SELECT ...
       (CASE when location = 'Hong Kong' then days / 7.0
             when location = 'Canberra' then days / 7.5
             when location = 'Sydney' then days / 7.25
        end) AS Hours

您可以使用LOWER()UPPER()来忽略区分大小写的匹配,例如LOWER(location) = LOWER('Hong Kong')

希望这有帮助!

相关问题