SQL选择列的最大值的行(在GROUP BY中有两个字段)

时间:2015-05-01 17:23:20

标签: sql sql-server greatest-n-per-group

这是我的基本查询(SQL Server):

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

生成一个像这样的表:

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

我想获取每个项目ID的Summ列最大的项目ID和业务ID。所以给出的例子中的第1行和第4行。我如何调整原始查询来执行此操作?

3 个答案:

答案 0 :(得分:2)

如果您可能有联系并希望返回两行,则应使用:

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

答案 1 :(得分:1)

您可以使用分析函数:

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;

希望有所帮助。

答案 2 :(得分:0)

您需要第二个聚合或分析功能。以下是第二种聚合的方法:

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

在一个不支持分析功能的系统上需要这种方法,幸运的是,它不包括SQL Server。