请帮我弄清楚如何获得这样的表格:
ID Name City
-- ---- ----
1 A 2
2 C 1
3 E 3
4 B 2
5 D 2
6 G 3
7 F 2
......按照这样排序:
ID Name City
-- ---- ----
1 A 2
4 B 2
5 D 2
7 F 2
3 E 3
6 G 3
2 C 1
换句话说,我希望首先根据城市名称的数量重新排序,然后按名称重新排序。 拥有更多名字的城市应该先行。
答案 0 :(得分:7)
这应该可以解决问题:
select c.* from c
inner join (
select City, count(*) as cnt from c group by City
) a
on c.City = a.City
order by a.cnt desc, c.name asc
答案 1 :(得分:0)
SELECT ID,NAME,CITY,(从AS T2中选择计数(*),其中T2.CITY = T1.CITY)作为CITYCOUNT FROM CITY T1订单由CITYCOUNT DESC,NAME;
OR
SELECT ID,NAME,CITY FROM AS T1 order by(从AS T2选择count(*),其中T2.CITY = T1.CITY)DESC,NAME;
您也可以这样做:
ALTER TABLE ADD COLUMN CITYCOUNT INT(11)DEFAULT 0;
更新T1(从CITY中选择CITY,计数(*)作为CITYCOUNT)T2 SET T1.CITYCOUNT = T2.CITYCOUNT其中T1.CITY = T2.CITY;
来自CITYCOUNT DESC,NAME的订单ID,NAME,CITY,CITYCOUNT来自T1订单
答案 2 :(得分:-1)
我认为您的示例不正确,有价值3的城市应该排在首位,为此您可以尝试此查询:
SELECT
ID, Name, City
FROM <TABLE>
ORDER BY City DESC, Name ASC;
希望这就是你想要的。
更新的答案:
SELECT
Id, Name, T.City
FROM <TABLE> T
INNER JOIN
(SELECT DISTINCT
City, Count(City) AS CITYCOUNT
FROM Table_7
GROUP BY City) TEMP ON TEMP.City = T.City
ORDER BY TEMP.CITYCOUNT DESC