SQL在不使用TOP的情况下显示值最小的行

时间:2015-11-04 07:57:58

标签: sql-server

我试图通过不使用top函数列出具有最小值的行。 enter image description here

这是我的代码,

> SELECT COUNT(SOH.SalesOrderNumber) AS NumberOfSales,  SP.Name FROM Person.StateProvince SP 
JOIN Person.Address A ON SP.StateProvinceID = A.StateProvinceID
JOIN Sales.SalesTerritory AS ST ON SP.TerritoryID = ST.TerritoryID
JOIN Person.BusinessEntityAddress BEA ON A.AddressID = BEA.AddressID
JOIN Sales.SalesOrderHeader AS SOH ON BEA.BusinessEntityID = SOH.CustomerID
WHERE ST.Name = 'Australia'
GROUP BY SP.Name

理想情况下,结果应该是 NumberOfSale名称 94塔斯马尼亚

谢谢!

1 个答案:

答案 0 :(得分:2)

这将是另一种选择:

SELECT NumberOfSales
    ,NAME
FROM (
    SELECT COUNT(SOH.SalesOrderNumber) AS NumberOfSales
        , SP.NAME
        , ROW_NUMBER() OVER (
            ORDER BY COUNT(SOH.SalesOrderNumber)) RN
    FROM Person.StateProvince SP
    INNER JOIN Person.Address A
        ON SP.StateProvinceID = A.StateProvinceID
    INNER JOIN Sales.SalesTerritory AS ST
        ON SP.TerritoryID = ST.TerritoryID
    INNER JOIN Person.BusinessEntityAddress BEA
        ON A.AddressID = BEA.AddressID
    INNER JOIN Sales.SalesOrderHeader AS SOH
        ON BEA.BusinessEntityID = SOH.CustomerID
    WHERE ST.NAME = 'Australia'
    GROUP BY SP.NAME
    ) RS
WHERE RN = 1