【发布时间】:2018-11-23 12:33:52
【问题描述】:
我有一个这样的查询(原来的要复杂得多)
select 0, 999, count(case when cond = 'aa' then 1 end) val1, sum(case when cond = 'aa' then amount else 0 end) amount1,
count(case when cond = 'bb' then 1 end) val2, sum(case when cond = 'bb' then amount else 0 end) amount2
from myTable
where amount between 0 and 999
union
select 1000, 2999, count(case when cond = 'aa' then 1 end) val1, sum(case when cond = 'aa' then amount else 0 end) amount1,
count(case when cond = 'bb' then 1 end) val2, sum(case when cond = 'bb' then amount else 0 end) amount2
from myTable
where amount between 1000 and 2999
union
...
有多个联合,选择更复杂。
我想简化它。为此,我使用了 with 子句
with q1 as(
select case when cond = 'aa' then 1 end val1, case when cond = 'aa' then amount else 0 end amount1,
case when cond = 'bb' then 1 end val2, case when cond = 'bb' then amount else 0 end amount2
)
select 0, 999, sum(val1) val1, sum(amount1) amount1, sum(val2) val2, sum(amount2) amount2
from q1 where amount between 0 and 999
union
select 1000, 2999, sum(val1) val1, sum(amount1) amount1, sum(val2) val2, sum(amount2) amount2
from q1 where amount between 1000 and 2999
union
....
但就我而言,这仍然很长。 plsql中是否有可能这样写
with q1 as (
select minVal, maxVal, count(case when cond = 'aa' then 1 end) val1, sum(case when cond = 'aa' then amount else 0 end) amount1,
count(case when cond = 'bb' then 1 end) val2, sum(case when cond = 'bb' then amount else 0 end) amount2
from myTable
where amount between minVal and maxVal
)
select * from q1 insideWhere minVal=0 and maxVal=999
union select * from q1 insideWhere minVal=1000 and maxVal=2999
union ...
或者任何其他解决方案?
【问题讨论】:
-
如果您能更详细地描述您的实际问题,您可能会得到一些更好的答案。 IE。原始查询寻址有什么问题?这样,我们或许能够为您提供更好的选择,而不仅仅是盲目地尝试遵循您唯一的方向(如果可能的话,这不一定是最好的)。
-
它与第一个查询大致相同,但(cond = 'aa' then 1 end 时的情况)条件更复杂,有超过 20 个 case 甚至更多 union 更多的数量步骤(在 x 和 y 之间)将根据所要求的内容而改变,并且我的表已经是 with 子句的结果