无法对包含聚合或子查询的表达式执行聚合功能-错误

时间:2018-11-06 02:14:45

标签: sql sql-server

我无法从数据库中获得最畅销的产品。这是我尝试过的代码:

SELECT productid 
FROM soldvia 
GROUP BY productid 
HAVING SUM(noofitems) =  (SELECT MAX(SUM(noofitems))
                          FROM soldvia 
                          GROUP BY productid);

我收到此错误:

  

第15层状态1的第68行的消息130
  无法对包含聚合或子查询的表达式执行聚合功能。

我不知道我在做什么错,请帮忙。

1 个答案:

答案 0 :(得分:1)

在SQL Server中,您可以将其编写为:

SELECT productid
FROM soldvia
GROUP BY productid
HAVING SUM(noofitems) = (SELECT TOP (1) SUM(noofitems)
                         FROM soldvia
                         GROUP BY productid
                         ORDER BY SUM(noofitems) DESC
                        );

不过,编写查询的更典型方法是使用RANK()或窗口函数:

SELECT productid
FROM (SELECT productid, SUM(noofitems) as numitems,
             RANK() OVER (ORDER BY SUM(noofitems) DESC) as seqnum
      FROM soldvia
      GROUP BY productid
     ) t
WHERE seqnum = 1;