使用函数 SUM?

Using the function 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 的名称?

您不能使用该别名 - 检查 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

聚合函数的约束需要在 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

您不能在 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