Query question on SQL Server 2014.
I've been having some trouble with a query to return the MAX values from various columns.
The current query I'm running is below, and this works fine to return the max value from the columns specified for each date.
SELECT ws.ExerciseID,
ws.Date,
(SELECT Max(v) FROM
(VALUES (WeightReps1), (WeightReps2), (WeightReps3), (WeightReps4), (WeightReps5)
, (WeightReps6), (WeightReps7), (WeightReps8), (WeightReps9), (WeightReps10)
)
AS value(v)
)
as [Max Weight]
FROM workoutsessions ws
join ExerciseCultures ec on ws.ExerciseID = ec.ExerciseID
where ec.Name = 'Bench Press'
So this shows the max from these columns. Fantastic. However each of the columns 'weightreps' column has an adjacent column for 'Reps'. I need to return the max value from the columns as above, but only where the adjacent 'reps' column is greater or equal to a value.
I've provided a sample below:
ExerciseID | WorkoutID | Date | WeightReps1 | Reps1 | Weightreps2 | Reps2 | Weightreps3 | Reps3
105 | 201 | 11/08/2014 | 50 | 9 | 65 | 3 | 75 | 1
105 | 202 | 13/08/2014 | 55 | 6 | 70 | 2 | 77 | 1
So in the above sample, if I only want to return the highest value where the 'reps' column is greater than two. I would return the value '70' as this is the highest value where the adjacent reps column is equal or greater than two.
I've tried the below code, but this will bring back the highest value where any of the reps columns are greater than two -- not helpful.
SELECT top 1 ec.Name, Date,
(SELECT Max(v)
FROM (VALUES (WeightReps1), (WeightReps2), (WeightReps3), (WeightReps4), (WeightReps5)
, (WeightReps6), (WeightReps7), (WeightReps8), (WeightReps9), (WeightReps10)
) AS value(v)
) as [Weight]
FROM workoutsessions ws
join ExerciseCultures ec on ws.ExerciseID = ec.ExerciseID
where
ec.Name = 'Bench Press'
and ws.reps1 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps2 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps3 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps4 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps5 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps6 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps7 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps8 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps9 >= '6'
or
ec.Name = 'Bench Press'
and ws.reps10 >= '6'
order by weight desc
Any ideas where I'm going wrong?
Thanks.