SQL选择CTE

时间:2015-12-22 09:06:05

标签: sql sql-server

我想要做的就是获得订单数量最多的城市名称。看起来很简单,但是当我运行这个代码时(我不得不使用CTE),我只得到订单数量,没有城市名称。

WITH CityOrder AS
(
    SELECT City 
    FROM Person.Address JOIN Sales.SalesOrderHeader 
        ON ShipToAddressID = AddressID
), 
CitiesOrders AS
(
    SELECT City, COUNT(City) AS "NoOfOrders"
    FROM CityOrder
    GROUP BY City
)
SELECT MAX("NoOfOrders") FROM CitiesOrders;

我尝试将最后一行更改为

SELECT City, MAX("NoOfOrders") FROM CitiesOrders;

然而,它显示了所有城市的订单。我很确定我没有看到一些简单的错误。有什么建议?

4 个答案:

答案 0 :(得分:1)

订购您的结果并获得前1名,但如果有几个城市的订单数相同,则会有关系:

...
SELECT TOP 1 WITH TIES * 
FROM CitiesOrders
ORDER BY NoOfOrders DESC

答案 1 :(得分:0)

试试这个!

select top 1 * from
(
SELECT City,count(1) as x 
    FROM Person.Address JOIN Sales.SalesOrderHeader 
        ON ShipToAddressID = AddressID
group by City
) order by x desc

答案 2 :(得分:0)

WITH CityOrder AS
(
SELECT City 
    FROM Person.Address JOIN Sales.SalesOrderHeader 
    ON ShipToAddressID = AddressID
),  
CitiesOrders AS
(
SELECT City, COUNT(City) AS "NoOfOrders"
    FROM CityOrder
   GROUP BY City
)
SELECT * from CitiesOrders order by "NoOfOrders" desc limit 1;

答案 3 :(得分:0)

你写的是完美的查询,但有一点缺失。您可以将查询与Group by一起使用。

SELECT City, MAX("NoOfOrders") FROM CitiesOrders group by City