使用给定条件创建SQL查询

时间:2014-11-20 17:24:19

标签: sql performance optimization

我有一个

形式的SQL查询
SELECT 
    SUM(some_col) 
FROM
    (some table name here)
WHERE 
    some_common_condition AND
    some_condition1 AND 
    some_condition2 AND
    column_A = 'X'
GROUP BY 
    column_A;

column_A有一些我目前运行此查询的值。现在,对于column_A的每个唯一值,都存在一些相关的条件。

例如,如果column_A有3个唯一值X,Y,Z,则所有三个都有some_common_condition以及与之相关的一些特定条件,即

  • 代表X - > some_condition1 AND some_condition2
  • 代表Y - > some_condition3 AND some_condition4
  • 代表Z - > some_condition5 AND some_condition6

我想结合所有这些条件并制作一个单一的SQL查询,这为SUM(some_col)的所有值(即column_A)提供了相应的X,Y,Z

现在一个显而易见的方法是

SELECT *
  FROM(SELECT SUM(some_col) AS val_X FROM (table) WHERE conditions_for_X UNION ALL
       SELECT SUM(some_col) AS val_Y FROM (table) WHERE conditions_for_X UNION ALL
       SELECT SUM(some_col) AS val_Z FROM (table) WHERE conditions_for_X -- UNION ALL a.s.o.
      )

我想知道一个只能访问数据库一次的解决方案。上面的查询使用3个select语句,三次命中DB,这对于可伸缩性原因是不好的。

1 个答案:

答案 0 :(得分:2)

这会回答你的问题吗?

SELECT SUM(some_col) FROM ...

WHERE 
  (column_A = 'X' AND some_condition1 AND some_condition2) OR
  (column_A = 'Y' AND some_condition3 AND some_condition4) OR
  (column_A = 'Z' AND some_condition5 AND some_condition6)

GROUP BY column_A;