将表格的几列组合起来为另一个查询设置变量的最简单方法是什么?
我想避免在我的查询中不断重复if if then语句
SELECT
CASE
WHEN team_id = away_team_id THEN away_score * 5
WHEN team_id = home_team_id THEN home_score * 5
END AS team_score_times_five,
CASE
WHEN team_id = away_team_id THEN away_score - 5
WHEN team_id = home_team_id THEN home_score - 5
END AS team_score_minus_five
FROM t1
相反,我宁愿设置一个变量
CASE
WHEN team_id = away_team_id THEN away_score
WHEN team_id = home_team_id THEN home_score
END AS team_score
然后更干净地查询
SELECT team_score * 5 AS team_score_times_five, team_score - 5 AS team_score_minus_five FROM t1
答案 0 :(得分:2)
只需使用FROM
SELECT team_score * 5 AS team_score_times_five,
team_score - 5 AS team_score_minus_five
FROM (
SELECT CASE
WHEN team_id = away_team_id THEN away_score
ELSE home_score END AS team_score
FROM t1
) t
答案 1 :(得分:1)
您也可以尝试common table expressions:
WITH common_table_expression AS (
SELECT
CASE
WHEN team_id = away_team_id THEN away_score
WHEN team_id = home_team_id THEN home_score
END AS team_score
FROM t1
)
SELECT
team_score * 5 AS team_score_times_five
, team_score - 5 AS team_score_minus_five
FROM common_table_expression
CTE允许您堆叠多个查询,这些查询将以更易读的方式嵌套,并且如果业务需求发生更改,将来更容易修改(具体取决于具体情况)。
This article有一个很棒的部分名为"使用公用表表达式来获得极其可读的SQL"这为你想要使用CTE的原因提供了额外的论据。