【问题标题】:Subtract two rows and insert into a third rowSubtract two rows and insert into a third row
【发布时间】:2022-12-02 07:53:52
【问题描述】:

I am trying to sum up two rows. I have a table1 as the below:

MEASURES APR MAY JUN JUL
Measure 1 61 67 79 62
Measure 2 56 75 52 70

I need to get the total of the two rows as the below:

MEASURES APR MAY JUN JUL
Total 117 142 131 132

I tried using the below statement:

SELECT TOP(1)
   'DEFICIT' AS [MEASURES]
    APR - lag(APR, 1, 0) OVER (ORDER BY [MEASURES]) AS APR
   ,MAY - lag(MAY, 1, 0) OVER (ORDER BY [MEASURES]) AS MAY
   ,JUN - lag(JUN, 1, 0) OVER (ORDER BY [MEASURES]) AS JUN
   ,JUL - lag(JUL, 1, 0) OVER (ORDER BY [MEASURES]) AS JUL
   FROM table1
   ORDER BY [MEASURES] DESC;

But doesn't result correctly. I am not sure how to get the difference. Can you please point me to some solution. Thanks in advance.

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:
    SELECT 'Total', SUM(APR), SUM(MAY), SUM(JUN), SUM(JUL)
    FROM table1
    

    【讨论】:

      猜你喜欢
      • 2022-12-02
      • 2022-12-01
      • 1970-01-01
      • 2022-12-02
      • 2022-11-09
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多