代码之家  ›  专栏  ›  技术社区  ›  Chan

如何得到不同行的差异

sql
  •  0
  • Chan  · 技术社区  · 6 年前

    name        date      price
    productA    Jan2019   3000
    productA    Feb2019   3500
    productA    Mar2019   3200
    productB    Jan2019   2500
    productB    Feb2019   2700
    productB    Mar2019   2800
    

    我想计算每个产品2019年3月和2019年2月的变化百分比。例如,对于productA,百分比为(3200-3500)/3500=-8.6%

    name         date        %change
    productA     Mar2019     -8.6
    productB     Mar2019     3.7
    

    如何编写sql命令? 谢谢

    2 回复  |  直到 6 年前
        1
  •  2
  •   Gordon Linoff    6 年前

    可以使用条件聚合。像这样:

    select name,
           (1 - 
            max(case when date = 'Mar2019' then price end) / 
            max(case when date = 'Feb2019' then price end) 
           )
    from t
    group by name
    
        2
  •  0
  •   PPJN    6 年前

    为了使这个过程更加干净,我建议将日期存储为日期,并将其设置为每月的第一天。这样就更容易连接了。你将加入产品和日期少于1个月的前一个月。如果没有上个月,我输入 NA

    create table #test  (
                            name    varchar(16)
                            ,[date] date
                            ,price  decimal(18,2)
                        )
    
    insert into #test
    values      ('productA',    '2019-01-01',   3000),
                ('productA',    '2019-02-01',   3500),
                ('productA',    '2019-03-01',   3200),
                ('productB',    '2019-01-01',   2500),
                ('productB',    '2019-02-01',   2700),
                ('productB',    '2019-03-01',   2800)
    
    
    select      a.name                      name
                ,format(a.date,'yyyyMM')    [date]
                ,case
                    when b.date is not null then cast(cast((a.price - b.price)/b.price * 100 as decimal(18,1)) as varchar(25)) + '%'
                    else 'NA'
                end                         change
    from        #test   a
    left join   #test   b   on      b.name = a.name
                                and b.[date] = dateadd(month,-1,a.date)
    
    
    drop table #test