从查询中获取最大值

时间:2016-10-30 07:32:53

标签: sql-server tsql

我需要使用AdventureWorks数据库(https://technet.microsoft.com/en-us/library/ms124438(v=sql.100).aspx)找到其家乡地址位于澳大利亚的所有客户的最常见客户名字。

我下面的代码给了我需要的答案(“Lacey”使用了25次),但它产生了561行。如何使用TOP xSET ROWCOUNT来操作结果,将此限制为1行而不

SELECT 
    FirstName, 
    COUNT(PP.FirstName) AS FirstNameCount
FROM
    Person.Person AS PP
    INNER JOIN Sales.Customer AS SC 
        ON SC.PersonID = PP.BusinessEntityID
    INNER JOIN Person.BusinessEntity AS PBE
        ON PBE.BusinessEntityID = PP.BusinessEntityID 
    INNER JOIN Person.BusinessEntityAddress AS PBEA
        ON PBEA.BusinessEntityID = PBE.BusinessEntityID
    INNER JOIN Person.AddressType AS PAT
        ON PAT.AddressTypeID = PBEA.AddressTypeID
    INNER JOIN Person.Address AS PA 
        ON PA.AddressID = PBEA.AddressID
WHERE
    PAT.AddressTypeID = 2 AND 
    StateProvinceID = 50 OR 
    StateProvinceID = 64 OR 
    StateProvinceID = 66 OR 
    StateProvinceID = 71 OR 
    StateProvinceID = 77
GROUP BY 
    FirstName
ORDER BY 
    FirstNameCount DESC

2 个答案:

答案 0 :(得分:1)

在查询结尾添加以下内容:

-- << the query you have here
OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY;

答案 1 :(得分:0)

我认为问题出在WHERE子句中。

如果你添加括号,你应该得到一个更好的结果集,即

WHERE
PAT.AddressTypeID = 2 AND 
(StateProvinceID = 50 OR 
StateProvinceID = 64 OR 
StateProvinceID = 66 OR 
StateProvinceID = 71 OR 
StateProvinceID = 77)

甚至更好的是在ie

中使用
WHERE PAT.AddressTypeID = 2 AND StateProvinceID IN (50,64,66,71,77)

我认为只显示第一行的限制可以通过MAX(COUNT(*))来实现