2

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?

joshschreuder
  • 1,413
  • 2
  • 18
  • 32
  • Heve you considered using CASE as in CASE WHEN t.MondayHrs < 8 THEN t.MondayHrs ELSE 8 END + CASE WHEN t.TuesdayHrs < 8 THEN t.TuesdayHrs ELSE 8 END + ...... – Steve Ford Nov 14 '12 at 23:45
  • [this post](http://stackoverflow.com/questions/124417/is-there-a-max-function-in-sql-server-that-takes-two-values-like-math-max-in-ne) might help you.. Though you're more looking for a `min` function. – Mike Christensen Nov 14 '12 at 23:45
  • 1
    @SteveFord, I did, but it looked extremely messy. – joshschreuder Nov 14 '12 at 23:46
  • User defined function looks good, I will look into it, thanks @MikeChristensen – joshschreuder Nov 14 '12 at 23:47

4 Answers4

6
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)
bummi
  • 27,123
  • 14
  • 62
  • 101
4

Try...

select least(t.MondayHrs,8) 
    + least(t.TuesdayHrs,8)
    + least(t.WednesdayHrs,8)
    + least(t.ThursdayHrs,8)
    + least(t.FridayHrs,8)
   ) as TotalHours
Quickpick
  • 163
  • 6
2

An alternate idea would be to use CASE. For example:

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
ItsPete
  • 2,363
  • 3
  • 27
  • 35
1

You can write a function for that like MySQL GREATEST.

Then you could do something like

select greatest(some_col, 8) +
       greatest(other_col, 8) + 
       ...
from your_table
juergen d
  • 201,996
  • 37
  • 293
  • 362