查询中的清洁案例陈述?

时间:2012-01-04 15:00:24

标签: sql variables alias

我正在进行插入,我插入的值之一计算如下:

SUM(Value1)/(
    CASE SUM(
        CASE Value2 > 0 
        THEN 1
        ELSE 0 
        END
    ) = 0 
    THEN 1 
    ELSE SUM(
        CASE Value2 > 0 
        THEN 1 
        ELSE 0 
        END
    )
)

内部CASE - 部分重复两次,将别名或变量设置为此值并使用该别名或变量会很好。

2 个答案:

答案 0 :(得分:1)

CTE回答......

WITH
  step1 AS
(
  SELECT
    SUM(value1)                            AS interimValue1
    SUM(CASE value2 > 0 THEN 1 ELSE 0 END) AS interimValue2,
    <other fields>
  FROM
    <a query>
)
SELECT
  interimValue / CASE interimValue2 = 0 THEN 1 ELSE interimValue2 END
FROM
  step1


SubQuery版本......

SELECT
  interimValue / CASE interimValue2 = 0 THEN 1 ELSE interimValue2 END
FROM
(
  SELECT
    SUM(value1)                            AS interimValue1
    SUM(CASE value2 > 0 THEN 1 ELSE 0 END) AS interimValue2,
    <other fields>
  FROM
    <a query>
)
  AS step1


或者,更具体到您发布的SQL,但不是通用案例的答案......

SUM(value1) / COALESCE(SUM(CASE WHEN value2 > 0 THEN 1 ELSE NULL END), 1)

(返回NULL,返回0允许COALESCE用1替换NULL。)

答案 1 :(得分:1)

SUM(Value1) / COALESCE(NULLIF(SUM(CASE WHEN Value2 > 0 THEN 1 ELSE 0 END), 0), 1)
如果NULLIF的结果等于NULL,则

SUM将产生0,否则它将返回SUM的结果。如果COALESCE不是NULLIF,则NULL会保留1的结果,否则将返回{{1}}。