使用聚合函数从子查询中获取特定行

时间:2015-04-03 06:07:04

标签: sql sql-server database

我试图从子查询中获取一个特定的行,但我不能在WHERE子句中使用聚合函数,并且我已经读过我应该使用HAVING子句但我不知道从哪里开始。

这是我当前的sql语句:

SELECT *
FROM
(
    select ID, SUM(BALANCE) AS Balance FROM bankacc GROUP BY ID
)A

我会得到:

ID | Balance

1  |  30

2  |  40

3  |  50

4  |  50

我需要MAX(Balance)的行,但我不知道从哪里开始,请帮忙。

3 个答案:

答案 0 :(得分:2)

你可以将它包装在子查询中:

SELECT q.id, max(q.b)
FROM
(
    select ID, SUM(BALANCE) b FROM bankacc GROUP BY ID
) q
group by q.id

或按照降序排序并获得第一条记录:

select top 1 ID, SUM(BALANCE) b FROM bankacc GROUP BY ID order by b desc
在MySQL中

你需要使用限制1而不是前1

答案 1 :(得分:2)

使用窗口功能:

DECLARE @t TABLE ( ID INT, Amount MONEY )

INSERT  INTO @t
VALUES  ( 1, 10 ),
        ( 1, 10 ),
        ( 1, 10 ),
        ( 2, 5 ),
        ( 2, 20 ),
        ( 3, 50 )


SELECT  ID ,
        Amount
FROM    ( SELECT    ID ,
                    SUM(Amount) AS Amount ,
                    RANK() OVER ( ORDER BY SUM(Amount) DESC ) AS rn
          FROM      @t
          GROUP BY  ID
        ) t
WHERE   rn = 1

TOPTIES

SELECT TOP 1 WITH TIES
        ID ,
        SUM(Amount) AS Amount
FROM    @t
GROUP BY ID
ORDER BY Amount   desc     

这些版本将返回总和最大的行,而不仅仅是前1行。

输出:

ID  Amount
3   50.00

答案 2 :(得分:0)

我认为这应该很简单。

- 这将只返回1条记录,即使MAX有相同数量的2条记录

SELECT  top 1 ID ,
        Amount
FROM    ( SELECT    ID ,
                    SUM(Amount) AS Amount 
          FROM      Table
          GROUP BY  ID
        ) t
Order by Amount desc,ID asc

使用窗口功能:这将返回您想要的内容。

SELECT  ID ,
        Amount
FROM    ( SELECT    ID ,
                    SUM(Amount) AS Amount ,
                    RANK() OVER ( ORDER BY SUM(Amount)  DESC ) AS rnk
          FROM      Table
          GROUP BY  ID
        ) t
WHERE   rnk = 1