枢轴和多列求和

时间:2018-07-16 18:49:59

标签: sql sql-server pivot

我有一个查询,该查询创建以下数据:

ID          LegacyID                type1 type2 date        value
1500000001  10070242801000000217    DF    RN    2018-05-24  -3.33000000
1500000002  10078387921000000217    PP    IN    2018-05-26  -11.00000000
1500000002  10078387921000000217    PP    RN    2018-05-26  -100.00000000
1500000003  10080625841000000217    DF    RN    2018-05-23  -3.33000000
1500000003  10080625841000000217    DF    RN    2018-05-23  99.000000

我正在尝试对类型字段上的数据进行透视,在对ID,LegacyID和日期字段进行分组时对值求和。

创建此:

id              legacyid                    date        DFRN          PPIN          PPRN
1500000001      10070242801000000217        2018-05-24  -3.33000000   0             0
1500000002      10078387921000000217        2018-05-26  0            -11.00000000   -100.00000000
1500000003      10080625841000000217        2018-05-23  95.67000000   0             0

请注意,我正在尝试将类型字段串联到它们的唯一组合中。

我已经尝试过几种枢轴突变,但是我似乎无法做到正确,我最近的尝试(无效)如下所示:

    select
        id,
        legacyid,
        [date],
        [DF]+[RN] as DFRN,
        [CR]+[CR] as CRCR,
        [CR]+[MR] as CRMR,
        [DF]+[DS] as DFDS,
        [DF]+[MR] as DFMR,
        [PP]+[DS] as PPDS,
        [PP]+[IN] as PPIN,
        [PP]+[RN] as PPRN,
    from (
    select
        tl.[id],
        r.[LegacyId],
        a.type1,
        bt.type2,   
        [Date],
        gl.TotalAmountUSD as [value]
    from
       ----long join
    where
        gh.IsActive = 1                             
    group by 
        tl.id,
        r.LegacyId,
        a.type1,
        bt.type2,
        [date])
    ) as bb
    pivot
    (
        sum(value)
        for rentalid in (
        [DF]+[RN] as DFRN,
        [CR]+[CR] as CRCR,
        [CR]+[MR] as CRMR,
        [DF]+[DS] as DFDS,
        [DF]+[MR] as DFMR,
        [PP]+[DS] as PPDS,
        [PP]+[IN] as PPIN,
        [PP]+[RN] as PPRN)
    ) as p

一个人如何对此进行关注?

1 个答案:

答案 0 :(得分:2)

只需使用条件聚合:

with t as (
      . . .
     )
select ID, LegacyID, date,
       sum(case when type1 = 'DF' and type2 = 'RN' then value end) as DFRN,
       sum(case when type1 = 'PP' and type2 = 'IN' then value end) as PPIN,
       sum(case when type1 = 'PP' and type2 = 'RN' then value end) as PPRN
from t
group by ID, LegacyID, date ;