简体   繁体   中英

SQL select row where SUM of a column is greatest (with two fields in GROUP BY)

Here's my basic query (SQL Server):

SELECT projectID, businessID, sum(number) AS summ
FROM table
GROUP BY projectID, businessID
ORDER BY projectID, sum(number) DESC

which produces a table like so:

         Project ID      Business ID    Summ
              1              1           63
              1              2           32 
              1              3            6
              2              3           45
              2              1           44
              2              2            3

I want to grab the project ID and business ID where the Summ column is greatest for each project ID. So rows 1 and 4 in the example given. How can I tweak the original query to do this?

If you might have ties and want to return both rows, you should use:

select * from
    (select projectID, businessID
      , sum(number) as Tot
      , max(sum(number)) over (partition by projectID) as MSum
      from Table
    group by projectID, businessID)
a
where a.tot = a.Msum

You can use analytic functions:

SELECT projectID,
       businessID,
       summ
  FROM(SELECT projectID,
              businessID,
              SUM(number) AS summ,
              ROW_NUMBER() OVER (PARTITION BY projectID
                                     ORDER BY SUM(number) DESC) AS rn
        FROM table
       GROUP
          BY projectID,
             businessID
      ) t
 WHERE rn = 1
 ORDER
    BY projectID;

Hope that helps.

You need a second aggregation or an analytic function. Here's a way to do it with a second aggregation:

WITH sums as (
  SELECT projectID, businessID, sum(number) AS summ
  FROM table
  GROUP BY projectID, businessID
)
SELECT sums.projectId, sums.businessId, sums.summ
FROM
  (
    SELECT projectID, MAX(summ) as ms
    FROM sums
    GROUP BY projectID
  ) ms
  JOIN sums
    ON sums.projectId = ms.projectId AND sums.summ = ms.ms

You would need this approach on a system that doesn't support analytic functions, which, luckily for you, does not include SQL Server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM