我有一个'吸引力的数据库表'每个景点都有县和/或城市的列。我需要按字母顺序显示县和城市的列表,以及每个县或城市的记录总数。
以下SQL查询工作正常,但COUNT显示每个只有一个,而不是每个县或城市的景点总数。
有人能告诉我如何将下面两个SQL语句组合在一起吗?
SQL:
SELECT entry, COUNT(entry) AS totalForEntry
FROM ( SELECT DISTINCT county AS entry
FROM venues
WHERE (county IS NOT NULL AND county <> '' )
UNION ALL
SELECT DISTINCT city as entry
FROM venues
WHERE (city IS NOT NULL
AND
city <> ''
)
) X GROUP BY entry ORDER BY entry ASC
结果:
Hove (1)
Inverness-shire (1)
Isle of Man (1)
Kent (1)
Lancashire (1)
Leeds (1)
Leicester (1)
Leicestershire (2)
Lincolnshire (1)
Liverpool (1)
以下有关计算县的工作,我需要它来统计城市并将其与上述查询相结合:
SELECT DISTINCT county, COUNT(county) AS Count
FROM venues
WHERE (county IS NOT NULL AND county <> '')
GROUP BY county ORDER BY county ASC
正确的结果应该是:
Hove (7)
Inverness-shire (3)
Isle of Man (12)
Kent (20)
Lancashire (34)
Leeds (31)
Leicester (5)
Leicestershire (53)
Lincolnshire (7)
Liverpool (43)
非常感谢提前。
答案 0 :(得分:1)
将DISTINCT
与GROUP BY
一起使用是没有意义的。你可以这样做:
SELECT county AS entry, COUNT(county) AS Count
FROM venues
WHERE (county IS NOT NULL AND county <> '')
GROUP BY county
UNION ALL
SELECT city as entry, COUNT(city) As Count
FROM venues
WHERE (city IS NOT NULL AND city <> '')
GROUP BY city
ORDER BY entry ASC