如何使用Sql server减去动态行结果

时间:2017-04-21 13:06:22

标签: sql sql-server

我有下表。

enter image description here

在此表中,月份行是动态的

我想获得以下输入,

enter image description here

任何人都知道获得输出的解决方案。

3 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

select Month, [2017-04], [2017-03], [2017-02], [2017-01]
from your_Table
where Month in ('A', 'B')

union all

select
    'C'
    T1.[2017-04] - T2.[2017-04], 
    T1.[2017-03] - T2.[2017-03], 
    T1.[2017-02] - T2.[2017-02], 
    T1.[2017-01] - T2.[2017-03]
from your_Table as T1
    left outer join your_Table as T2 on T2.Month = 'A'
where T1.Month = 'B'

答案 1 :(得分:0)

非常奇怪的问题但是:

SELECT Month
     , [2017-04]
     , [2017-03] 
     , [2017-02]
     , [2017-01]  
FROM (
  SELECT Month
     , [2017-04]
     , [2017-03] 
     , [2017-02]
     , [2017-01] 
     , 1 as mOrder
  FROM  table 
  WHERE Month in ('B','A')
  UNION ALL
  SELECT 'C'
     , sum(case Month = 'A' then [2017-04]*-1 else [2017-04] end)
     , sum(case Month = 'A' then [2017-03]*-1 else [2017-04] end)
     , sum(case Month = 'A' then [2017-02]*-1 else [2017-04] end)
     , sum(case Month = 'A' then [2017-01]*-1 else [2017-04] end)
     , 2 as morder
  FROM table 
  WHERE Month in ('B','A')
  )
ORDER BY Month, mOrder

答案 2 :(得分:0)

如果我理解正确,您将需要动态添加行,并且检查应始终使用前一行完成,因此我将使用以下代码:

 insert into dbo.tab1 
 select 'C' as month
       , t.[2017-04] - tprev.[2017-04] as [2017-04]
       , t.[2017-03] - tprev.[2017-03] as [2017-03]
       , t.[2017-02] - tprev.[2017-02] as [2017-02]
       , t.[2017-01] - tprev.[2017-01] as [2017-01]
 from ( 
         select ROW_NUMBER() OVER(ORDER BY month) AS Nr
             , month
             , [2017-04]
             , [2017-03]
             , [2017-02]
             , [2017-01] 
         from dbo.tab1 
       ) t left join (
                 select ROW_NUMBER() OVER(ORDER BY month) AS Nr
                    , month
                    , [2017-04]
                    , [2017-03]
                    , [2017-02]
                    , [2017-01] 
                from dbo.tab1 
           ) tprev on t.Nr = (tprev.Nr -1) -- join with prev row to get the difference

您可以在预先生成Month值的循环中添加它,并在此处传递它是一个参数。 我生成了行号并加入了它,因为如果你有超过前两行,你需要一个额外的列来加入。 您可以查看此here的工作版本。