在SQL Server 2014上查询问题。
我在查询时遇到了一些问题,无法从各列返回MAX值。
我正在运行的当前查询在下面,这可以正常返回每个日期指定的列的最大值。
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'
因此,这显示了这些列的最大值。太棒了。但是,每个列的“weightreps”列都有一个“Reps”的相邻列。我需要从上面的列返回最大值,但仅限于相邻的'reps'列大于或等于某个值的位置。
我在下面提供了一个示例:
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
所以在上面的示例中,如果我只想返回'reps'列大于2的最高值。我会返回值'70',因为这是相邻reps列等于或大于2的最高值。
我已尝试过以下代码,但这会带回任何代表列大于2的最高值 - 没有帮助。
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
我出错的任何想法?
感谢。
答案 0 :(得分:2)
您可以更改此子查询:
SELECT Max(v)
FROM
(
VALUES
(WeightReps1), (WeightReps2), (WeightReps3), (WeightReps4), (WeightReps5),
(WeightReps6), (WeightReps7), (WeightReps8), (WeightReps9), (WeightReps10)
) AS value(v)
到此:
SELECT Max(w)
FROM
(
VALUES
(WeightReps1, Reps1), (WeightReps2, Reps2),
(WeightReps3, Reps3), (WeightReps4, Reps4),
(WeightReps5, Reps5), (WeightReps6, Reps6),
(WeightReps7, Reps7), (WeightReps8, Reps8),
(WeightReps9, Reps9), (WeightReps10, Reps10)
) AS value(w, r)
WHERE
r >= ... /* some value */
答案 1 :(得分:1)
您可以在CASE
子句中使用VALUES
表达式:
SELECT ws.ExerciseID,
ws.Date,
(SELECT Max(v) FROM
(VALUES (CASE WHEN Reps1 > 6 THEN WeightReps1 ELSE NULL END),
(CASE WHEN Reps2 > 6 THEN WeightReps2 ELSE NULL END),
(CASE WHEN Reps3 > 6 THEN WeightReps3 ELSE NULL END),
... etc
)
AS value(v)
)
as [Max Weight]
FROM workoutsessions ws
join ExerciseCultures ec on ws.ExerciseID = ec.ExerciseID
where ec.Name = 'Bench Press'
这样,WeightRepsx
值将被忽略,如果'邻近&#39}。根据您的要求,Repsx
值不大于特定值。
当然这是相当丑陋的,但它是一个选项,因为你的表没有正确规范化。