我在SQL Server 2008数据库中有两个SQL表,如下所示:
Customer
--------
ID
Name
Order
-----
ID
CustomerID
Total
我需要弄清楚客户订购的订单数量是多少。此时,我已经到了这里:
SELECT MAX([OrderCount]) FROM (
SELECT COUNT(o.[ID]) as 'OrderCount'
FROM [Order] o
GROUP BY o.[CustomerID]
)
当我执行此语句时,我收到一条消息,上面写着“语法不正确”)'“。我的子查询有效。这意味着问题在于SELECT MAX([OrderCount]),但是对我来说一切看起来都是正确的(授予,我不是一个sql高手)。我在这做错了什么?我是否正确地攻击了这个SQL查询?
谢谢
答案 0 :(得分:3)
你基本上就在那里:
SELECT MAX([OrderCount]) FROM (
SELECT COUNT(o.[ID]) as 'OrderCount'
FROM [Order] o
GROUP BY o.[CustomerID]
) t
最后需要别名。
在没有子查询的情况下编写此代码的另一种方法是:
SELECT top 1 COUNT(o.[ID]) as OrderCount
FROM [Order] o
GROUP BY o.[CustomerID]
order by OrderCount desc
答案 1 :(得分:0)
或者你可以这样做:
SELECT max(COUNT(o.[ID])) as 'OrderCount'
FROM [Order] o
GROUP BY o.[CustomerID]
答案 2 :(得分:0)
OVER子句的另一个选项
SELECT TOP 1 MAX(COUNT(o.[ID])) OVER() AS OrderCount
FROM [Order] o
GROUP BY o.[CustomerID]
SQLFiddle上的演示