2012-08-01 53 views
0

如何將整數查詢結果限制爲1.返回2爲1,返回1爲1,返回0.5爲0.5,因爲它返回是< = 1.我不想修改表格,我只是想修改結果。如何將sql整數查詢結果限制爲<= 1

這是我的確切查詢。

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

我正在使用postgres。

+0

只是一個快速的注意,你不能在一個整數返回0.5。您需要將其轉換爲其他數字才能獲得。 – 2012-08-02 17:06:44

回答

2

要限制,你會做這樣的事情:

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') 
     ); 
+0

增加'> ='代替'>' – shahkalpesh 2012-08-01 15:24:07

+1

'LEAST(number,1)'? – Wiseguy 2012-08-01 15:24:24

+0

@shahkalpesh我看到了。但是,這有點毫無意義,你不覺得嗎? – 2012-08-01 15:24:44

1

使用LEAST功能,文檔:http://www.postgresql.org/docs/8.3/static/functions-conditional.html。此外,檢查出GREATEST

SELECT LEAST(1, <your value>) 

編輯代替GREATEST以最少

+0

你的意思是最少? – 2012-08-01 15:26:17

+0

我真的認爲你的意思是最低 – 2012-08-01 15:27:14

+0

是啊,我可能是最低限度:)。謝謝。我很快懶惰。 – bpgergo 2012-08-01 15:34:18

0

試試這個:

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;