如何在同一个Select语句中复制确切字段的值?
我有什么:
SELECT
FIELD1,
FIELD2,
CASE WHEN FIELD3 <> FIELD4
THEN CASE WHEN SUBSTRING(FIELD10,1,3) = FIELD5
THEN (FIELD1 * FIELD3) + FIELD4
ELSE (FIELD1 / FIELD3) + FIELD4
END
END AS CUSTOM_FIELD1,
-- does the same CASE only to set it to another field.
-- i don't want to make the same case again, I want it to be smarter and use the same value as CUSTOM_FIELD1 without needing to calculate again.
CASE WHEN FIELD3 <> FIELD4
THEN CASE WHEN SUBSTRING(FIELD10,1,3) = FIELD5
THEN (FIELD1 * FIELD3) + FIELD4
ELSE (FIELD1 / FIELD3) + FIELD4
END
END AS CUSTOM_FIELD2
我敢打赌有一种方法可以让这段代码变得更聪明,更干净,我只是不知道如何。
答案 0 :(得分:3)
SELECT
FIELD1,
FIELD2,
CUSTOM_FIELD1,
CUSTOM_FIELD1 AS CUSTOM_FIELD2
FROM
(
SELECT
FIELD1,
FIELD2,
CASE WHEN FIELD3 <> FIELD4
THEN CASE WHEN SUBSTRING(FIELD10,1,3) = FIELD5
THEN (FIELD1 * FIELD3) + FIELD4
ELSE (FIELD1 / FIELD3) + FIELD4
END
END AS CUSTOM_FIELD1
FROM TABLE
) AS SUB