【问题标题】:Over partition by 2 columns SQL Server按 2 列 SQL Server 分区
【发布时间】: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


    【解决方案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;
    

    【讨论】:

    • 所以我可以简单地写成:sum(c * e) over (partition by a,rnc ) as sumProduct 吗?不再需要询问原因,因为现在我正在过滤日期和 rnc
    • @viorelmunteanu 。 . .如果您不需要外壳,请将其移除。
    猜你喜欢
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多