【发布时间】:2015-09-22 11:34:31
【问题描述】:
我参加了我之前的一个练习并增加了一些复杂性。 你可以在下面找到我原来的问题: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
我得到了这个:
现在我想计算由 rnc 和日期(a 列)分区的 sumProduct。 这该怎么做?我尝试使用 group by,但我遇到了来自 select 的不相等数字和我分组依据的项目数的问题。
所以,我想像这样重写:
(sum(c * e) over (partition by a and partition by rnc )) as sumProduct
【问题讨论】:
标签: sql sql-server sql-server-2008 sql-server-2012 window-functions