2012-11-14 30 views
1

我想限制特定字段,以便它們不超過特定值。SELECT字段中的字段值

例如,像這樣就足夠了,其中,I可以指定字段應不超過8:

SELECT (
     cap(t.MondayHrs,8) 
     + cap(t.TuesdayHrs,8) 
     + cap(t.WednesdayHrs,8) 
     + cap(t.ThursdayHrs,8) 
     + cap(t.FridayHrs,8) 
     ) as TotalHours 

如果MondayHrs = 7,則它應該被添加到作爲TotalHours 7. 如果MondayHrs = 10,那麼它應該被添加到TotalHours作爲8(我的上限值)

有什麼內置到T-SQL,可以方便嗎?

+0

HEVE你認爲使用情況下,在CASE WHEN t.MondayHrs <8 THEN t.MondayHrs ELSE 8 END + CASE WHEN t.TuesdayHrs <8 THEN t.TuesdayHrs ELSE 8 END + ...... –

+0

[This post](http://stackoverflow.com/questions/124417/is-there-a-max-function-in-sql-server-that-takes -two-values-math-max-in-ne)可能會幫助你..雖然你更多的是尋找一個'min'函數。 –

+1

@SteveFord,我做到了,但看起來非常混亂。 – joshschreuder

回答

5
create function Cap (@Value float,@maxValue float) Returns float 
as 
begin 
Declare @Result float 
if @Value > @maxValue select @[email protected] else select @[email protected] 
Return @Result 
end; 

使用

Select dbo.Cap(1,10),dbo.Cap(11,10) 
+0

這是我去的路徑,除了我從這裏使用的UDF:http://stackoverflow.com/a/124474/324817 – joshschreuder

1

你可以寫一個像MySQL GREATEST那樣的函數。

然後,你可以做這樣的事情

select greatest(some_col, 8) + 
     greatest(other_col, 8) + 
     ... 
from your_table 
2

另一種想法是使用CASE。例如:

SELECT ( 
     (CASE WHEN t.MondayHrs > 8 THEN 8 ELSE t.MondayHrs END) 
     + (CASE WHEN t.TuesdayHrs > 8 THEN 8 ELSE t.TuesdayHrs END) 
) as TotalHours 
1

嘗試...

select least(t.MondayHrs,8) 
    + least(t.TuesdayHrs,8) 
    + least(t.WednesdayHrs,8) 
    + least(t.ThursdayHrs,8) 
    + least(t.FridayHrs,8) 
    ) as TotalHours