【问题标题】:Trying to add Value and Maximum value by Using Row Number Function尝试使用行号函数添加值和最大值
【发布时间】:2021-08-31 00:20:47
【问题描述】:

表 A

Row Number     ID    orderType    value     Reference Code
1              1      A            5          2
2              1      A.1          2          4
1              2      A            6          5
2              2      A.1          2          1

我正在尝试得到这个结果表 B

Row Number     ID    orderType    value     Reference Code
1              1      A            7          4
1              2      A            8          5

我正在使用 SQL Server 2016 并尝试在 Like a TABLE B 中实现结果,我可以在其中添加值并获得最大的参考代码。

我同时使用 Row_Number 和 Sum,但无法获得所需的结果。

我的查询是

SELECT 
  ID,
  Ordertype ,
  ROW_NUMBER() over (Partition by Id order by OrderType ) as Row Number,
  sum([Value]) over( partition by id) as Value,
  Max(Reference Code) as Reference Code

From Table A

where row number = 1

【问题讨论】:

  • 我建议将您的参考代码更改为可以正确排序为文本的内容。

标签: sql sql-server sql-server-2016 window-functions


【解决方案1】:

使用窗口函数:SUM() 用于总数 valueMIN() 用于orderTypeMAX() 用于Reference_Code

SELECT DISTINCT ID,
       MIN(orderType) OVER (PARTITION BY ID) orderType,
       SUM(value) OVER (PARTITION BY ID) value,
       MAX(Reference_Code) OVER (PARTITION BY ID) Reference_Code
FROM TableA

请参阅demo

【讨论】:

    【解决方案2】:

    为什么不直接使用聚合?

    select min(row_number), id, min(ordertype), 
           sum(value), max(referencecode)
    from a
    group by id;
    

    【讨论】:

      【解决方案3】:

      我已尝试为您编写查询

      SELECT 
        id,
        (SELECT TOP 1 ot FROM test WHERE id=t.id ORDER BY ot) ot,
        ROW_NUMBER() OVER (PARTITION BY id ORDER BY id ) as row_num,
        SUM(val) as Value,
        MAX(ref_code) as ReferenceCode
      FROM test as t
      GROUP BY id;
      

      查看工作演示SQLFiddle

      【讨论】:

        猜你喜欢
        • 2018-07-16
        • 2015-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-24
        • 2016-03-18
        • 1970-01-01
        相关资源
        最近更新 更多