Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cap field value in SELECT

I am trying to cap particular fields so that they don't exceed a particular value.

For example, something like this would suffice, where I can specify that a field should not exceed 8:

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

If MondayHrs = 7, then it should be added to TotalHours as 7. If MondayHrs = 10, then it should be added to TotalHours as 8 (my capped value)

Is there anything built into T-SQL that could facilitate this?

like image 685
joshschreuder Avatar asked Jul 25 '26 20:07

joshschreuder


2 Answers

Try...

select least(t.MondayHrs,8) 
    + least(t.TuesdayHrs,8)
    + least(t.WednesdayHrs,8)
    + least(t.ThursdayHrs,8)
    + least(t.FridayHrs,8)
   ) as TotalHours
like image 151
Quickpick Avatar answered Jul 27 '26 09:07

Quickpick


create function Cap (@Value float,@maxValue float) Returns float 
as
begin
Declare @Result float
if @Value > @maxValue select @Result=@Maxvalue else select @Result=@Value
Return @Result
end;

usage

Select dbo.Cap(1,10),dbo.Cap(11,10)
like image 32
bummi Avatar answered Jul 27 '26 08:07

bummi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!