在行计算后创建别名?

时间:2012-04-09 23:00:37

标签: mysql sql

有一种方法可以在计算后创建一个别名吗?

在实践中有更好的方法来写这个:

select
    case when aaa ... then then else end AS ALIAS1,
    case when bbb ... then then else end AS ALIAS2,
    case when ccc ... then then else end AS ALIAS3,
    /* the sum of previous aliases */
    case when aaa ... then then else end +
    case when bbb ... then then else end +
    case when ccc ... then then else end AS ALIAS_SUM

提前谢谢

1 个答案:

答案 0 :(得分:2)

你可以这样做。这样你就不会两次处理这些案件了。

SELECT *, ALIAS1 + ALIAS2 + ALIAS3 AS ALIAS_SUM
FROM 
(
    SELECT 
        CASE WHEN aaa ... THEN ... ELSE END AS ALIAS1,
        CASE WHEN bbb ... THEN ... ELSE END AS ALIAS2,
        CASE WHEN ccc ... THEN ... ELSE END AS ALIAS3
    FROM...
) AS casequeries