基于两个变量求和记录



我正在努力达到一个月内达到的点击次数,我尝试了几个SUM公式,但我被卡住了,你能帮我解决这个问题吗?我已经从DB中检索到了第1个月和第2个月的总点击量,正如你所看到的,有2种源类型,1和2,以及几个点击类型1到6。目标是找到按源分组的周期中每种类型的命中数。

Source  type        number         time
1        1          200            2015-02-01 00:00:25.000
1        2          350            2015-02-01 00:00:25.000
1        3           50            2015-02-01 00:00:25.000
1        4         1000            2015-02-01 00:00:25.000
2        1          360            2015-01-01 00:00:20.000
2        2           30            2015-01-01 00:00:20.000
2        3          500            2015-01-01 00:00:20.000
2        4          250            2015-01-01 00:00:20.000
1        1          200            2015-01-01 00:00:20.000
1        2          350            2015-01-01 00:00:20.000
1        3           50            2015-01-01 00:00:20.000
1        4         1000            2015-01-01 00:00:20.000
2        1          360            2015-02-01 00:00:25.000
2        2           30            2015-02-01 00:00:25.000
2        3          500            2015-02-01 00:00:25.000
2        4          250            2015-02-01 00:00:25.000

Ex二月点击次数

Source1 Sum(type1+type4) of 2015-01-01  - Sum(type1+type4) of 2015-02-01

我知道这看起来很困惑,但这是我唯一能解释的方法。

提前感谢

卡洛斯

您希望将金额拆分为每个月的单独列吗?

select 
    Source, 
    sum(case when time >= '20150101' and time < '20150201' then number else 0 end) as Jan,
    sum(case when time >= '20150201' and time < '20150301' then number else 0 end) as Feb
from
    table
where
    type in (1,4)
group by
    source

如果您还需要使用不同类型的单独列,那么您必须将该类型也添加到case语句中。

最新更新