在SQL Select中复制值get

时间:2011-09-13 17:58:37

标签: sql select sybase

如何在同一个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

我敢打赌有一种方法可以让这段代码变得更聪明,更干净,我只是不知道如何。

1 个答案:

答案 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