计算并显示第3行中2行的%更改

时间:2018-04-19 13:17:27

标签: sql-server sql-server-2012

我有一张表来比较每年的月度销售数据。该表将每月更新一次,将记录替换为上个月 - 同年和前一年的销售数据。

Month_Year || Sale_Vol || #Sales || Average_Price
  Mar-17   ||   1250   ||   25   ||   50
  Mar-18   ||    900   ||   20   ||   45

我需要在附加行中显示%更改((3月18日)/(3月17日) - 1)* 100,如下所示

Month_Year || Sale_Vol || #Sales || Average_Price
  Mar-17   ||   1250   ||   25   ||   50
  Mar-18   ||    900   ||   15   ||   60
Prcnt_Chng ||    -28   ||  -40   ||   20

我无法弄清楚如何实现这一目标。这是我到目前为止所写的内容,但它并不优雅。

SELECT 'Percentage Change',NULL, 
100.0 * ((select * from Tbl where [Month_Year] = left(CONVERT(VARCHAR(8),DATEADD(mm,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)),112),6))-(select * from Tbl where [Month_Year] = left(CONVERT(VARCHAR(8),DATEADD(mm,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE())-12,0)),112),6)))/(select * from Tbl where [Month_Year] = left(CONVERT(VARCHAR(8),DATEADD(mm,-1,DATEADD(mm,DATEDIFF(mm,0,GETDATE()),0)),112),6));

而且,我收到错误:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

2 个答案:

答案 0 :(得分:1)

首先,错误的原因是,计数不匹配。即100是单一物质,不属于子查询。但是在subuquery的旁边,你会返回多个列。如果你纠正了这个问题,那么你得到了一张桌子(可能与你的桌子不同) 我试图查询你..!

编辑:

   select * from yourtable  -- get previous table
   union
   select 'Prcnt_Chng ',(  -- to get calculated row
   ((((select Sale_Vol from yourtable where Month_Year = 'Mar-18')/  --value of Sale_Vol of mar 18
   (select Sale_Vol from yourtable where Month_Year = 'Mar-17'))-1)  --value of Sale_Vol of mar 18. divided and sub by 1 
   100),                                                              -- mul by 100
   ((((select [#Sales] from yourtable where Month_Year = 'Mar-18')/  --value of [#Sales] of mar 18
   (select [#Sales] from yourtable where Month_Year = 'Mar-17'))-1)  --value of [#Sales] of mar 18. divided and sub by 1
   100),                                                              -- mul by 100
   ((((select Average_Price from yourtable where Month_Year = 'Mar-18')/  --value of Average_Price of mar 18
   (select Average_Price from yourtable where Month_Year = 'Mar-17'))-1)  --value of Average_Price of mar 18. divided and sub by 1
   100))                                                                   -- mul by 100

答案 1 :(得分:1)

考虑到您的表中只有两行,您可以尝试此查询

;with cte as (
    select
        *, rn = row_number() over (order by Month_Year)
    from
        myTable
)

select * from myTable
union all
select
    'Prcnt_Chng', 100 * b.Sale_Vol / a.Sale_Vol - 100
    , 100 * b.[#Sales] / a.[#Sales] - 100
    , 100 * b.Average_Price / a.Average_Price - 100
from
    cte a
    join cte b on a.rn + 1 = b.rn
where a.rn = 1