尝试使用行号函数添加值和最大值

Trying to add Value and Maximum value by Using Row Number Function

Table一个

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

我正在尝试得到这个结果Table 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

使用 window 函数: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

我已经尝试为您编写查询

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

为什么不直接使用聚合?

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