0

我有以下两个表:

TABLE: area
*City_ID   *Number   Name
--------   -------   ----
SUR        1         Fleetwood
SUR        2         Whalley
SUR        3         Guildford
SUR        4         Newton
SUR        5         Cloverdale
SUR        6         South Surrey
ABB        1         Abbotsford East
ABB        2         Abbotsford West
ABB        3         Aberdeen
ABB        4         Bradner
ABB        5         Central Abbotsford
ABB        6         Matsqui
ABB        7         Poplar
ABB        8         Sumas Mountain
ABB        9         Sumas Prairie

TABLE: city
*ID        Name
---        ----
SUR        Surrey
ABB        Abbotsford
LAN        Langley

使用以下语句:

SELECT DISTINCT area.City_ID, city.Name
FROM area
INNER JOIN city
WHERE area.City_ID = city.ID

我得到:

SELECT:
City_ID    city.Name
-------    ---------
SUR        Surrey
ABB        Abbotsford

但是我该如何选择以下内容:

SELECT:
City_ID    city.Name    area_COUNT
-------    ---------    ----------
SUR        Surrey       6
ABB        Abbotsford   9

每个对应area_COUNT的行数在哪里?areaCity_ID

4

4 回答 4

2

使用GROUP BY代替DISTINCT

SELECT city.City_ID, city.Name, COUNT(*)
FROM area
INNER JOIN city
WHERE area.City_ID = city.ID
GROUP BY city.ID
于 2012-07-17T08:49:30.097 回答
1

您还应该在 Group by 子句中添加名称

SELECT area.City_ID, city.Name, count(*) as area_COUNT 
FROM area 
INNER JOIN city 
WHERE area.City_ID = city.ID 
GROUP BY area.City_ID,City.Name
于 2012-07-17T08:55:07.690 回答
0

在末尾添加分组依据

SELECT area.City_ID, city.Name, count(*) as area_COUNT
FROM area
INNER JOIN city
WHERE area.City_ID = city.ID
GROUP BY area.City_ID
于 2012-07-17T08:49:32.907 回答
0

使用 GROUP BY 而不是 DISTINCT:

SELECT city.City_ID, city.Name, COUNT(*) FROM area INNER JOIN city WHERE area.City_ID = city.ID GROUP BY city.ID

于 2012-07-17T10:06:49.587 回答