【问题标题】:how to limit a sql integer query result to <=1如何将 sql 整数查询结果限制为 <=1
【发布时间】:2012-08-01 15:20:24
【问题描述】:

如何将整数查询结果限制为 1。返回 2 为 1,返回 1 为 1,返回 0.5 为 0.5,因为它

这是我的确切查询。

select ((select "V01" from sports where "UID" = '1') * 1.0 ) / 
(select "V01" from master where "BALL" = 'REQUIREMENT') ;

我正在使用 postgres。

【问题讨论】:

  • 请注意,您不能以整数形式返回 0.5。你需要转换成其他的东西,比如数字才能得到它。

标签: sql postgresql integer


【解决方案1】:

为了限制,你可以这样做:

select 
    case 
        when yourNumber >= 1 then 1
        else yourNumber
    end
...

然后您只需将此概念应用于您的查询。

正如 Wiseguy 所说,您也可以这样做:

select LEAST(yourNumber, 1)

,因为这是 postgresql。

第一个解决方案适用于任何 ANSI SQL 兼容的数据库。

更新

应用于您的查询,我认为(如果我正确理解您想要的内容)会是这样的:

select LEAST(1,
               ((select "V01" from sports where "UID" = '1') * 1.0 ) / 
               (select "V01" from master where "BALL" = 'REQUIREMENT')
       );

【讨论】:

  • LEAST(number, 1) 怎么样?
  • @shahkalpesh 我看到了。但这有点毫无意义,你不觉得吗?
  • @Adrian:是的。对不起,我现在明白了。已编辑。
  • 谢谢你,谢谢你给我准确的语法!
  • 很高兴为您提供帮助。不要忘记投票/接受对您最有帮助的答案。
【解决方案2】:

使用LEAST 函数,文档:http://www.postgresql.org/docs/8.3/static/functions-conditional.html。另外,也请查看GREATEST

SELECT LEAST(1, <your value>)

EDIT 将 GREATEST 替换为 LEAST

【讨论】:

  • 我真的认为你的意思是最少
  • 是的,我的意思可能是最少的:)。谢谢。我又快又懒。
【解决方案3】:

试试这个:

select CASE 
         WHEN ((select V01 from sports where UID = '1') * 1.0 ) / 
               (select V01 from master where BALL = 'REQUIREMENT') >= 1
         THEN 1
         ELSE ((select V01 from sports where UID = '1') * 1.0 ) / 
               (select V01 from master where BALL = 'REQUIREMENT')
       END;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-14
    • 2011-03-08
    • 2015-01-19
    • 1970-01-01
    • 2010-10-01
    • 2017-05-04
    • 2019-10-25
    • 2011-03-24
    相关资源
    最近更新 更多