2

请帮我弄清楚如何获得这样的表格:

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

换句话说,我希望它首先根据城市中名称的数量进行重新排序,然后再根据名称进行排序。拥有更多名称的城市应该先行。

4

3 回答 3

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

这是SQL 小提琴

于 2013-09-19T07:07:17.253 回答
0

SELECT ID,NAME,CITY,(select count(*) from AS T2 where T2.CITY = T1.CITY) as CITYCOUNT FROM AS T1 order by CITYCOUNT DESC,NAME ;

或者

SELECT ID,NAME,CITY FROM AS T1 order by (select count(*) from AS T2 where T2.CITY = T1.CITY)DESC,NAME ;

或者,您也可以这样做:

ALTER TABLE ADD 列 CITYCOUNT INT(11) 默认 0;

UPDATE T1(选择 CITY,count(*) as CITYCOUNT from group by CITY) T2 SET T1.CITYCOUNT = T2.CITYCOUNT where T1.CITY = T2.CITY;

SELECT ID,NAME,CITY,CITYCOUNT FROM AS T1 order by CITYCOUNT DESC,NAME

于 2013-09-19T07:48:08.473 回答
-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
于 2013-09-19T06:54:45.553 回答