过度分区2列SQL Server

时间:2015-09-22 11:34:32

标签: sql sql-server sql-server-2008 sql-server-2012 window-functions

我参加了之前的一项练习并增加了一些复杂性。 您可以在select case with "over partition by"

下找到我原来的问题

场景:(使用SQL Server 2012)

 create table #testing (b varchar (20), a date, c int, e int)

 insert into #testing (b,a,c,e)
 values
    ('xf_1m','2015-03-02','1','3'),
    ('xf_3m','2015-03-02','2','5'),
    ('xf_5y','2015-03-02','4','2'),
    ('xf_10y','2015-03-02','3','6'),
    ('ay_10y','2015-03-02','7','2'),
    ('adfe_1m','2015-03-02','2','5'),
    ('xm_1m','2013-02-01','7','2'),
    ('xf_15y','2013-02-01','1','8'),
    ('xf_20y','2013-02-01','10','1')

使用此查询后:

select
    b, a, c, e,
    substring (b, 1, CHARINDEX ('_', b) - 1) rnc,
    substring(b, CHARINDEX('_', b) + 1, LEN (b)) rnb,
    case 
        when b like 'xf%' then -- 
            (sum(c * e) over (partition by a )) end as sumProduct
into #testing2
from #testing

select 
    *,
    case 
        when b like 'xf%' then -- 
        (sum(c * e) over (partition by a )) end as sumProduct
into #testing3
from #testing2

select * 
from #testing3

我得到了这个:

enter image description here

现在我只想计算由rnc和date(列a)分区的sumProduct。 这该怎么做?我尝试使用group by,但是我遇到了选择中的不等号和我正在分组的项目数量的麻烦。

所以,我喜欢以某种方式重写这个

 (sum(c * e) over (partition by a and partition by rnc )) as sumProduct

1 个答案:

答案 0 :(得分:1)

我不确定您使用临时表的原因,但只需将它们包含在partition by列表中即可按多列进行分区:

select *,
       (case when b like 'xf%' 
             then sum(c * e) over (partition by a, rnd )
        end) as sumProduct
into #testing3
from #testing2;