在 MySQL 中一起使用 Distinct、Count 和 Group
Using Distinct, Count and Group together in MySQL
我有一个 'attractions' 的数据库 table,每个景点都有县 and/or 市的列。我需要按字母顺序显示一个县市列表,以及每个县市的记录总数。
下面的 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)
非常感谢。
将 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
我有一个 'attractions' 的数据库 table,每个景点都有县 and/or 市的列。我需要按字母顺序显示一个县市列表,以及每个县市的记录总数。
下面的 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)
非常感谢。
将 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