SUM中的条件逻辑

时间:2014-10-16 14:29:44

标签: sql sql-server

我目前正在通过UNION ALL查询组合两个表,并对结果执行SUM和GROUP BY操作。一切都按预期工作,但我有一个独特的要求,我似乎无法弄清楚如何实现。 我的目标是编写一个SQL,上面写着“当DEV_AGE列为> = 12时,将REVENUE值设置为该列为12时的值”。我提供下面的代码,因为我知道这个描述可能有点令人困惑:

收入表:

ACC_YR    DEV_AGE   STATE   REVENUE LOSS
2012        3         MA     4000    0
2012        6         MA     8000    0
2012        9         MA     12000   0
2012        12        MA     16000   0

LOSS表:

ACC_YR    DEV_AGE   STATE   REVENUE LOSS
2012        3         MA     0       2000
2012        6         MA     0       7000
2012        9         MA     0       9000
2012        12        MA     0       10000
2012        15        MA     0       14000
2012        18        MA     0       14000
2012        21        MA     0       14000
2012        24        MA     0       15000
2012        27        MA     0       17000

UNION ALL,GROUP BY,SUM之后的表:

ACC_YR    DEV_AGE   STATE   REVENUE LOSS
2012        3         MA     4000    2000
2012        6         MA     8000    7000
2012        9         MA     12000   9000
2012        12        MA     16000   10000
2012        15        MA     0       14000
2012        18        MA     0       14000
2012        21        MA     0       14000
2012        24        MA     0       15000
2012        27        MA     0       17000

我想要完成的事情:

ACC_YR    DEV_AGE   STATE   REVENUE LOSS
2012        3         MA     4000    2000
2012        6         MA     8000    7000
2012        9         MA     12000   9000
2012        12        MA     16000   10000
2012        15        MA     16000   14000
2012        18        MA     16000   14000
2012        21        MA     16000   14000
2012        24        MA     16000   15000
2012        27        MA     16000   17000

换句话说,我的收入在DEV_AGE为12时停止开发(REVENUE表中除了DEV_AGE为12之外没有行),但我希望每个DEV_AGE超过12,等于收入在12的最后表

1 个答案:

答案 0 :(得分:2)

这是一种方法,它使用窗口函数计算12岁的收入,然后计算分配它的逻辑:

select acc_yr, dev_age, state,
       (case when dev_age > 12 then rev12 else revenue end) as revenue, loss
from (select l.acc_yr, l.dev_age, l.state, r.revenue, l.loss,
             max(case when l.dev_age = 12 then r.revenue end) over (partition by l.acc_yr, l.state) as rev12
      from loss l left join
           revenue r
           on l.acc_yr = r.acc_yr and l.dev_age = r.dev_age and l.state = dev.state
     ) lr;