在select语句中创建一个新列

时间:2015-04-07 20:35:16

标签: sql postgresql casting case

下面是使用的代码。

 select address, area,
 case area
 when area < 1500 then 'small'
 when area > 2500 then 'large'
 else 'medium'
 end as size
 from listings
 where zip = 95677;

有了这个,我想创建一个新的列,告诉你房子是大还是小,具体取决于区域大小。

这是我得到的错误,我不确定如何投射它以使其工作。如果这是解决方案,就像提示说的那样。

  

第3行:当面积<1时1500然后'小'            ^提示:没有运算符匹配给定的名称和参数类型。您可能需要添加显式类型转换。

1 个答案:

答案 0 :(得分:1)

正确的语法是:

 select address, area,
        (case when area < 1500 then 'small'
              when area > 2500 then 'large'
              else 'medium'
         end) as size
 from listings
 where zip = 95677;

case有两种形式。以上是case when <condition>形式,其中when条款是完全形成的条件。另一种形式更像是C语言中的switch语句:case area when 10 then 'ten' when 20 then 'twenty' . . .。此表单只能测试单个表达式的相等性。

相关问题