我的代码写成:
SELECT name, age,
CASE WHEN abs(10 - mean(valueLeft)) < abs(10 - mean(valueRight)) THEN stddev(valueLeftMagnitude) ELSE stddev(valueRightMagnitude) END as value1,
CASE WHEN abs(10 - mean(valueLeft)) < abs(10 - mean(valueRight)) THEN mean(valueLeftMagnitude) ELSE mean(valueRightMagnitude) END as value2,
CASE WHEN abs(10 - mean(valueLeft)) < abs(10 - mean(valueRight)) THEN median(valueLeftMagnitude) ELSE median(valueRightMagnitude) END as value3
FROM table
GROUP BY name, age
由于所有三个CASE中的WHEN语句相同,我不想重复它们。有没有办法做到这一点?
示例:我想要像 -
这样的东西SELECT name, age,
CASE WHEN abs(10 - mean(valueLeft)) < abs(10 - mean(valueRight))
THEN stddev(valueLeftMagnitude) ELSE stddev(valueRightMagnitude) END as value1,
THEN mean(valueLeftMagnitude) ELSE mean(valueRightMagnitude) END as value2,
THEN median(valueLeftMagnitude) ELSE median(valueRightMagnitude) END as value3
FROM table
GROUP BY name, age
请帮忙。
答案 0 :(得分:0)
嵌入式选择可以确保您只进行一次case
计算:
SELECT perprocessed.name, perprocessed.age, stddev(perprocessed.valueMagnitude), mean(perprocessed.valueMagnitude), median(perprocessed.valueLeftMagnitude) from
(SELECT
name,
age,
CASE WHEN abs(10 - mean(valueLeft)) < abs(10 - mean(valueRight)) THEN valueLeftMagnitude ELSE valueRightMagnitude END as valueMagnitude
FROM table) as perprocessed
GROUP BY perprocessed.name, perprocessed.age
答案 1 :(得分:0)
您的查询非常易读,我认为复制粘贴表达式并没有什么不妥。如果您只想进行一次此评估,则查询会稍微复杂一些,因为您需要分两步执行:
SELECT
CASE WHEN which = 'left' THEN stddev_left ELSE stddev_right END AS value1,
CASE WHEN which = 'left' THEN mean_left ELSE mean_right END AS value2,
CASE WHEN which = 'left' THEN median_left ELSE median_right END AS value3
FROM
(
SELECT
name,
age,
CASE WHEN abs(10 - mean(valueLeft)) < abs(10 - mean(valueRight))
THEN 'left' ELSE 'right' END AS which,
stddev(valueLeftMagnitude) AS stddev_left,
stddev(valueRightMagnitude) AS stddev_right,
mean(valueLeftMagnitude) AS mean_left,
mean(valueRightMagnitude) AS mean_right,
median(valueLeftMagnitude) AS median_left,
median(valueRightMagnitude) median_right
FROM table
GROUP BY name, age
) grouped;