我正在通过一本书(“使用sqlite”)和Northwind数据库学习sqlite3.我编写了以下代码,按照其所在城市的客户数量订购客户,然后按名称按字母顺序排列.
SELECT ContactName,Phone,City as originalCity FROM Customers ORDER BY ( SELECT count(*) FROM Customers WHERE city=originalCity) DESC,ContactName ASC
通常(不仅仅是sqlite),最好一次对所有值(城市)进行计数,并使用连接来构造查询:
SELECT ContactName,Customers.City as originalCity FROM Customers JOIN (SELECT city,count(*) cnt FROM Customers GROUP BY city) Customers_City_Count ON Customers.city = Customers_City_Count.city ORDER BY Customers_City_Count.cnt DESC,ContactName ASC
(为了防止,就像你的情况一样,对于相同的值(城市)计算多次计数)