使用函数SUM?

时间:2015-01-20 20:33:03

标签: sql sum

我有这个问题:

Select t1.col5,
       t1.col6,
       SUM(CASE WHEN t2.col1 = 'A' THEN t2.col2 ELSE 0
                WHEN t2.col1 = 'B' THEN t2.col2 * -1 ELSE 0
       END) AS price,
       SUM(CASE WHEN t2.col1 = 'C' THEN t2.col2 + 100  ELSE 0
       END) AS bonus
       FROM t1, t2
       WHERE t1.col1 = t2.col4
       AND (price + bonus ) <> 0
      GROUP BY  t1.col5,
                t1.col6

但我不能(price + bonus ) <> 0?我有这样的消息:价格无效的标识符! 如何在WHERE中使用SUM的名称?

3 个答案:

答案 0 :(得分:1)

对聚合函数的约束需要在HAVING子句中完成:

Select t1.col5,
       t1.col6,
       SUM(CASE WHEN t2.col1 = 'A' THEN t2.col2 ELSE 0
                WHEN t2.col1 = 'B' THEN t2.col2 * -1 ELSE 0
       END) AS price,
       SUM(CASE WHEN t2.col1 = 'C' THEN t2.col2 + 100  ELSE 0
       END) AS bonus
       FROM t1, t2
       WHERE t1.col1 = t2.col4

      GROUP BY  t1.col5,
                t1.col6
    having SUM(CASE WHEN t2.col1 = 'A' THEN t2.col2 ELSE 0
                WHEN t2.col1 = 'B' THEN t2.col2 * -1 ELSE 0
       END) + SUM(CASE WHEN t2.col1 = 'C' THEN t2.col2 + 100  ELSE 0
       END) <> 0

答案 1 :(得分:0)

您不能使用该别名 - 请查看SQL查询中的操作顺序:http://www.bennadel.com/blog/70-sql-query-order-of-operations.htm

你需要尝试这样的事情:

Select t1.col5,
       t1.col6,
       SUM(CASE WHEN t2.col1 = 'A' THEN t2.col2 ELSE 0
                WHEN t2.col1 = 'B' THEN t2.col2 * -1 ELSE 0
       END) AS price,
       SUM(CASE WHEN t2.col1 = 'C' THEN t2.col2 + 100  ELSE 0
       END) AS bonus
       FROM t1, t2
       WHERE t1.col1 = t2.col4
       AND (SUM(CASE WHEN t2.col1 = 'A' THEN t2.col2 ELSE 0 WHEN t2.col1 = 'B' THEN t2.col2 * -1 ELSE 0 END)
            +
           SUM(CASE WHEN t2.col1 = 'C' THEN t2.col2 + 100  ELSE 0 END)) <> 0
          GROUP BY  t1.col5,
                    t1.col6

答案 2 :(得分:0)

您不能在WHERE子句中使用列别名(或者,就此而言,聚合)。所以你想要做的是使用子查询或将聚合放在HAVING子句中。我将在下面显示子查询,我认为这更容易,因为您不必重现所有键击(您需要在HAVING子句中使用聚合本身,而不是它们的别名):

SELECT * FROM (
    Select t1.col5,
           t1.col6,
           SUM(CASE WHEN t2.col1 = 'A' THEN t2.col2 ELSE 0
               WHEN t2.col1 = 'B' THEN t2.col2 * -1 ELSE 0
           END) AS price,
           SUM(CASE WHEN t2.col1 = 'C' THEN t2.col2 + 100  ELSE 0
           END) AS bonus
       FROM t1, t2
      WHERE t1.col1 = t2.col4
      GROUP BY  t1.col5,
            t1.col6
) WHERE (price + bonus ) <> 0