分区超过 2 列 SQL 服务器
Over partition by 2 columns SQL Server
我做了我以前的一个练习,并增加了一些复杂性。
您可以在以下位置找到我的原始问题:
场景:(使用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。
这该怎么做?我尝试使用分组依据,但我遇到了来自 select 的不相等数字和我分组依据的项目数的问题。
所以,我想像这样重写:
(sum(c * e) over (partition by a and partition by rnc )) as sumProduct
我不确定你为什么要使用临时表,但你可以通过将它们包含在 partition by
列表中来按多个列进行分区:
select *,
(case when b like 'xf%'
then sum(c * e) over (partition by a, rnd )
end) as sumProduct
into #testing3
from #testing2;
我做了我以前的一个练习,并增加了一些复杂性。
您可以在以下位置找到我的原始问题:
场景:(使用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。 这该怎么做?我尝试使用分组依据,但我遇到了来自 select 的不相等数字和我分组依据的项目数的问题。
所以,我想像这样重写:
(sum(c * e) over (partition by a and partition by rnc )) as sumProduct
我不确定你为什么要使用临时表,但你可以通过将它们包含在 partition by
列表中来按多个列进行分区:
select *,
(case when b like 'xf%'
then sum(c * e) over (partition by a, rnd )
end) as sumProduct
into #testing3
from #testing2;