问题描述
|
在大学考试中有一个问题。是否可以在“ 0”子句中使用聚合函数。
我一直以为这是不可能的,我也找不到任何可能的例子。但是我的答案被标记为错误,现在我想知道在哪种情况下可以在ѭ1中使用聚合函数。同样,如果不可能的话,那么可以得到一个描述该规范的链接。
解决方法
您还没有提到DBMS。假设您正在使用MS SQL Server,我发现了一条不言自明的T-SQL错误消息:
\“聚合可能不会出现在
WHERE子句,除非它位于
HAVING子句中包含的子查询
或选择列表,并且该列为
汇总是外部参考\“
http://www.sql-server-performance.com/
还有一个在子查询中可能的示例。
显示具有5个或更多订单的所有客户和最小订单(其他订单为NULL):
SELECT a.lastname,a.firstname,( SELECT MIN( o.amount )
FROM orders o
WHERE a.customerid = o.customerid
AND COUNT( a.customerid ) >= 5
)
AS smallestOrderAmount
FROM account a
GROUP BY a.customerid,a.lastname,a.firstname ;
更新。
上面的代码可以在SQL Server和MySQL中运行,但不会返回我期望的结果。下一个更接近。我想这与在查询子查询联接中使用的字段customerid
,GROUPED BY和外表的第一种情况下的PRIMARY KEY有关,而在第二种情况下则没有。
显示所有具有5个或更多订单的客户ID和订单数(其他订单则显示NULL):
SELECT o.customerid,( SELECT COUNT( o.customerid )
FROM account a
WHERE a.customerid = o.customerid
AND COUNT( o.customerid ) >= 5
)
AS cnt
FROM orders o
GROUP BY o.customerid ;
, HAVING就像带有聚合函数的WHERE一样,或者您可以使用子查询。
select EmployeeId,sum(amount)
from Sales
group by Employee
having sum(amount) > 20000
要么
select EmployeeId,sum(amount)
from Sales
group by Employee
where EmployeeId in (
select max(EmployeeId) from Employees)
, 您不能直接在WHERE子句中使用集合;这就是HAVING子句的作用。
您可以使用在WHERE子句中包含汇总的子查询。
, 更新查询:
select id from t where id < (select max(id) from t);
它将选择表t中除最后一行以外的所有内容。
, SELECT COUNT( * )
FROM agents
HAVING COUNT(*)>3;
请参阅下面的更多链接:
http://www.w3resource.com/sql/aggregate-functions/count-having.php#sthash.90csRM4I.dpuf][1]
有任何疑问请致电我:85110 51548
http://www.w3resource.com/sql/aggregate-functions/count-having.php
, 另一个解决方案是将聚合函数移至标量用户定义函数
创建您的功能:
CREATE FUNCTION getTotalSalesByProduct(@ProductName VARCHAR(500))
RETURNS INT
AS
BEGIN
DECLARE @TotalAmount INT
SET @TotalAmount = (select SUM(SaleAmount) FROM Sales where Product=@ProductName)
RETURN @TotalAmount
END
在where子句中使用功能
SELECT ProductName,SUM(SaleAmount) AS TotalSales
FROM Sales
WHERE dbo.getTotalSalesByProduct(ProductName) > 1000
GROUP BY Product
参考文献:
1。
2。
希望可以帮助某人。