Firebird group by with sum并选择最大值

问题描述 投票:0回答:1

表名为:tbl_A

cname       emp          amount
client1     employeeA    100
client2     employeeA    500
client3     employeeA    200

结果应该是

cname       emp          amount
client2     employeeA    800

原因:client2的最大值为800,即所有客户中employeeS的总和。

我试过使用这段代码

select cname, emp, sum(amount)
from tbl_A 
group by cname, emp

它给了我不同的结果。

如果金额与其他客户相同,那么它将选择第一个1。

是否可以在一行结果中完成?

sql firebird firebird2.5
1个回答
0
投票

你去:

SELECT
  temp.cname,
  temp.emp,
  (SELECT
     SUM(amount)
   FROM tbl_a
   WHERE emp = temp.emp)
FROM (SELECT FIRST 1
        cname,
        emp
      FROM tbl_a
      ORDER BY amount DESC) as temp

UPDATE

SELECT
  emp,
  MAX(cname) as cname,
  (SELECT SUM(tbl_a.amount)
   FROM tbl_a
   WHERE tbl_a.emp = temp.emp)
FROM tbl_a as temp
GROUP BY 1
© www.soinside.com 2019 - 2024. All rights reserved.