针对给定条件优化SQL查询

时间:2014-10-20 07:02:15

标签: sql database oracle optimization

我对表格有疑问:

select SUM(some_column) from (table) 

where 

IF x then a

ELSE y then b

ELSE z then c

...

现在在我的JAVA代码中,我为每个不同的值(x,y,z,...)调用此查询,这会返回所需的总和。我的目标是计算总和对于所有这些价值观,即

Total = SUM_for_x + SUM_for_y + SUM_for_z + ....

现在,当然,我正在为数据库中的每一个这样的价值,这是昂贵的。我可以在一个单一的查询中优化这个,它为我做的工作,只打了一次数据库?

2 个答案:

答案 0 :(得分:0)

假设您只对总金额感兴趣而不是部分金额且条件相互排斥,您可以这样做:

SELECT SUM(some_column)
  FROM (table)
 WHERE (a)
    OR (b)
    OR (c)
    OR ...

另一种方式(如果您的条件不相互排斥)将是:

SELECT SUM(some_column)
  FROM(SELECT SUM(some_column) AS some_column FROM (table) WHERE (a) UNION ALL
       SELECT SUM(some_column) AS some_column FROM (table) WHERE (b) UNION ALL
       SELECT SUM(some_column) AS some_column FROM (table) WHERE (c) -- UNION ALL a.s.o.
      )

答案 1 :(得分:0)

SELECT SUM(case when x then a end) sum_a, 
       SUM(case when y then b end) sum_b, 
       SUM(case when z then c end) sum_c
  FROM <table>

并用Java总结

或在SQL中获取总数:

SELECT SUM(case when x then a end) sum_a + 
       SUM(case when y then b end) sum_b + 
       SUM(case when z then c end) sum_c 
  FROM <table>