MySQL 每个办公室邮政编码的查询频率
MySQL Query Frequency of Zip Codes per Offices
我正在尝试编写一个 MySQL 查询,以查看哪些邮政编码对我们的客户来说最常出现,并且需要帮助来完成它。我的 select 语句末尾的 office 字段可以是每个邮政编码 1 到 10 种可能性。
我将如何修复此查询以获得最常见的邮政编码以及 10 个可能的办公室中的哪个恰好在该邮政编码中有一个位置?
SELECT SUBSTRING(zip_code, 1, 5) AS zip,
COUNT(*) AS freq, office
FROM customer_billing
WHERE status != 'deleted'
GROUP BY zip
ORDER BY freq DESC
我正在寻找的示例输出:
zip freq office
---- ---- ----
92101 450 office_A, office_B
02124 300 office_A, office_C, office_D
07713 110 office_B
使用 GROUP_CONCAT
和 DISTINCT
。使用 DISTINCT
是必要的,因为对于给定的邮政编码,给定的办公室可能会出现多次。
SELECT SUBSTRING(zip_code, 1, 5), COUNT(*) AS freq,
GROUP_CONCAT(DISTINCT office ORDER BY office DESC SEPARATOR ',')
FROM customer_billing
WHERE status != 'deleted'
GROUP BY SUBSTRING(zip_code, 1, 5)
ORDER BY freq DESC
您可以使用group_concat
This function returns a string result with the concatenated non-NULL
values from a group. It returns NULL if there are no non-NULL values.
The full syntax is as follows:
SELECT SUBSTRING(zip_code, 1, 5) AS zip,
COUNT(*) AS freq, GROUP_CONCAT(office)
FROM customer_billing
WHERE status != 'deleted'
GROUP BY zip
ORDER BY freq DESC
我正在尝试编写一个 MySQL 查询,以查看哪些邮政编码对我们的客户来说最常出现,并且需要帮助来完成它。我的 select 语句末尾的 office 字段可以是每个邮政编码 1 到 10 种可能性。
我将如何修复此查询以获得最常见的邮政编码以及 10 个可能的办公室中的哪个恰好在该邮政编码中有一个位置?
SELECT SUBSTRING(zip_code, 1, 5) AS zip,
COUNT(*) AS freq, office
FROM customer_billing
WHERE status != 'deleted'
GROUP BY zip
ORDER BY freq DESC
我正在寻找的示例输出:
zip freq office
---- ---- ----
92101 450 office_A, office_B
02124 300 office_A, office_C, office_D
07713 110 office_B
使用 GROUP_CONCAT
和 DISTINCT
。使用 DISTINCT
是必要的,因为对于给定的邮政编码,给定的办公室可能会出现多次。
SELECT SUBSTRING(zip_code, 1, 5), COUNT(*) AS freq,
GROUP_CONCAT(DISTINCT office ORDER BY office DESC SEPARATOR ',')
FROM customer_billing
WHERE status != 'deleted'
GROUP BY SUBSTRING(zip_code, 1, 5)
ORDER BY freq DESC
您可以使用group_concat
This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values. The full syntax is as follows:
SELECT SUBSTRING(zip_code, 1, 5) AS zip,
COUNT(*) AS freq, GROUP_CONCAT(office)
FROM customer_billing
WHERE status != 'deleted'
GROUP BY zip
ORDER BY freq DESC