SQL Max和Sum

时间:2011-08-18 19:42:00

标签: sql

以下是我正在使用的查询:

SELECT 
   County,
   Code,
   Sum(PaidAmount) AS TotalPaid
FROM
   Counties
GROUP BY
   County,
   Code

返回集合:

County     Code         TotalPaid
Brown      99           210.21
Lyon       73           322.22
Lyon       88           533.22
Lincoln    22           223.21

我正在寻找的是一个查询,它将返回显示县的行和每个县的最大TotalPaid的代码。我需要的结果集的一个例子如下所示(注意里昂,自里昂以来被删除了73,88的总支付金额更高):

County     Code         TotalPaid
Brown      99           210.21
Lyon       88           533.22
Lincoln    22           223.21

5 个答案:

答案 0 :(得分:2)

我无法测试这个,但RANK应该解决这个问题:

SELECT x.County, x.Code x.TotalPaid
    ,RANK() OVER 
    (PARTITION BY x.County ORDER BY x.TotalPaid DESC) AS 'RANK'
FROM

(SELECT 
   County,
   Code,
   Sum(PaidAmount) AS TotalPaid
FROM
   Counties
GROUP BY
   County,
   Code) x
WHERE Rank = 1

答案 1 :(得分:1)

我认为你需要做类似下面的事情。在我复习我写的内容之前,我刚刚被叫走了,但希望它会给你足够的指针。一些RDBMS不允许“where country,TotalPaid = select value,value”构造但你可以解决这个问题

select 
   County,
   Code,
   TotalPaid
from (SELECT 
       County,
       Code,
       Sum(PaidAmount) AS TotalPaid
     FROM
       Counties
     GROUP BY
       County,
       Code ) tbl
 where County, TotalPaid = (select County, 
                                 max(TotalPaid)
                             FROM
                                 Counties
                             GROUP BY
                                 County,
                                 Code ) tbl2

答案 2 :(得分:0)

   SELECT 
   c.County,
   c.Code,
   Sum(c.PaidAmount) AS TotalPaid
   FROM
   Counties c
   WHERE
   c.Code in (select max(c2.code) from counties c2 where c2.county = c.county)
   GROUP BY
   c.County,
   c.Code

这个应该可以工作,虽然我还没有测试过

答案 3 :(得分:0)

您必须使用窗口函数来执行此操作。虽然你想要的东西很容易用英语表达,但遗憾的是它并不容易在SQL中表达。这应该做你需要的:

select
    County, Code, TotalPaid
from
(
SELECT 
   County,
   Code,
   sum(PaidAmount) AS TotalPaid
FROM
   Counties
GROUP BY
   County, Code
) source

where (row_number() over (partition by County order by TotalPaid desc)) = 1

答案 4 :(得分:-2)

这是一个更新的解决方案:

select c1.county, c1.code, c1.paidAmount 
from counties c1
inner join (
  select county, max(paidAmount) paidAmount 
  from counties 
  group by county) c2 
on c1.county=c2.county and c1.paidAmount=c2.paidAmount;

请注意,如果某个县有多个最高付款,则会返回共享该最大值的所有行。