我怎样才能得到最大值的总和?

时间:2018-04-04 20:19:15

标签: sql-server

我需要获取每个跟踪号(TN)的最大成本,然后将按OrderNo分组的值相加。 这是一张桌子:

 +----+-----+-------+
 |TNo |cost| OrderNo|
 +----+-----+-------+
 | 1  | 5  | 12     |
 | 1  | 4  | 12     |
 | 2  | 6  | 12     |
 | 2  | 3  | 12     |
 | 3  | 3  | 15     |
 | 4  | 2  | 15     |
 | 4  | 3  | 15     |
 +----+-----+-------+

这就是我想要的结果:

 +--------+-----+
 | OrderNo| Sum |
 +--------+-----+
 | 12     | 11  | (6+5)
 | 15     | 6   | (3+3)
 +--------+-----+

这是我到目前为止所做的,但是这对于跟踪编号的所有实例都是最大值。例如,在上表中,对于订单#12,它将加总5+5+6+6。我只想求最大值(5+6)

SELECT ol.OrderNo, SUM(t.maxCost)
   FROM (
     SELECT 
       ol.TrackingNumber, MAX(ol.Cost) maxCost
       FROM OzLink ol GROUP BY ol.TrackingNumber) t
  JOIN OzLink ol ON ol.TrackingNumber=t.TrackingNumber
   GROUP BY ol.OrderNo

**另外,我是这项工作的新手并在stackoverflow上提出问题,所以我很感激您对这个问题的反馈意见!

4 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT ol.OrderNo, SUM(ol.maxCost)
   FROM (
     SELECT 
       ol.TrackingNumber, MAX(ol.Cost) maxCost, ol.OrderNo
       FROM OzLink ol GROUP BY ol.TrackingNumber,ol.OrderNo) ol
   GROUP BY ol.OrderNo

答案 1 :(得分:2)

您可以从以下cte中受益:

CREATE TABLE mytab
    (
      TNo INT,
      Cost INT,
      OrderNo INT
    )

insert into mytab values (1,5,12)
insert into mytab values (1,4,12)
insert into mytab values (2,6,12)
insert into mytab values (2,3,12)
insert into mytab values (3,3,13)
insert into mytab values (4,2,13)
insert into mytab values (4,3,13)

;with cte (TNo,OrderNo,maxcost) as (
   select TNo,OrderNo,Max(Cost) as maxcost
   from mytab
   group by TNo, OrderNo
)
select OrderNo,SUM(maxcost) 
from cte
group by OrderNo

答案 2 :(得分:1)

有几种方法,如下面的答案。但是您也可以使用以下查询,并在子查询中创建基于OrderNo和TN的行号以及按成本DESC排序,然后仅返回最高成本。

SELECT OrderNo,
    SUM(Cost) As Cost
FROM
(
    SELECT ROW_NUMBER() OVER(PARTITION BY OrderNo, TN ORDER BY Cost DESC) AS HighestCost,
        Cost,
        OrderNo,
        TN
    FROM TableName 
) AS Data
WHERE HighestCost = 1
GROUP BY OrderNo

enter image description here

答案 3 :(得分:1)

与另一个答案相同

declare @T TABLE (TNo INT, Cost INT, OrderNo INT);
insert into @T values (1,5,12), (1,4,12), (2,6,12), (2,3,12), (3,3,15), (4,2,15), (4,3,15);
select t.OrderNo, sum(t.cost) 
from ( select OrderNo, cost 
            , ROW_NUMBER() over (partition by TNo, OrderNo order by cost desc) as rn
       from @T
     ) t 
where t.rn = 1 
group by t.OrderNo;  

OrderNo     
----------- -----------
12          11
15          6