2017-04-21 41 views
-3

我有下表。如何使用Sql服務器減去動態行結果

enter image description here

在這個表月份行是動態

我想下面的輸入,

enter image description here

任何人知道的解決方案,使輸出。

+1

如果它有更多的行(例如100行)你的邏輯輸出將如何? –

+0

你在哪裏得到行C的值? –

+0

我需要獲得新的行。您可以使用任何文本而不是C。月值爲動態 –

回答

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' 
+0

Andy,如果桌子上有100行,這將不起作用... upvoted,因爲邏輯是正確的。 –

+0

@冰塔當然不會。但OP在評論中提到,期望的結果應該是用兩個指定行B和A減去數據。它看起來很奇怪 - 但這是原始要求:*「即使有100列也要減去B行 - 一行」 * –

+0

是的正確。 [2017-04],[2017-03],[2017-02],[2017-01]這些值是動態的。我想減去B行 - 一行 –

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 
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 

您可以將此i在預先生成月份值的循環中,並在此處傳遞它是一個參數。 我生成了行號並加入了它,因爲如果您的行數多於前兩行,則需要添加一列。 你可以檢查這個here的工作版本。