mysql - 在 MySQL 查询中的一系列联合选择后无法创建总计行
问题描述
在我们的后端,我们将居住在给定国家的用户及其相关数据隔离到不同的数据源中。例如,有一个数据源是新加坡用户和他们的交易数据,另一个是日本用户和他们的交易数据,等等。
我在 Redash 中创建了一个查询,它构建了两列数据——国家名称和用户——它按预期工作。但是,我无法按照本文中推荐的方法将总计行添加到底部:http ://webdevzoom.com/ultimate-guide-count-subtotal-grand-total-mysql/ 。
GROUP BY Country WITH ROLLUP 不会产生总计行;相反,它只是重复最后一行的注册数。文章第 III.1 节中的建议似乎是最合适的,但我的实现在别名上返回“表 source1.all_signups 不存在”错误。作为参考,Redash在构建查询时需要选择一个数据源,而我选择的源是“source1”。
查询如下:
SELECT *
FROM
(SELECT "Country1" AS Country,
count(id) AS Users
FROM users
UNION SELECT "Country2" AS Country,
count(id) AS Users
FROM source2.users
UNION SELECT "Country3" AS Country,
count(id) AS Users
FROM source3.st_users
UNION SELECT "Country4" AS Country,
count(id) AS Users
FROM source4.st_users
...
UNION SELECT "CountryN" AS Country,
count(id) AS Signups
FROM sourceN.st_users
GROUP BY Country
ORDER BY Signups DESC
) AS all_signups
UNION SELECT
"GRAND TOTAL" AS Country,
SUM(Signups) AS Signups
FROM all_signups
解决方案
我能够解决这个问题,并想分享我的答案。关键是使用变量。我还更改了方向,将总计放在查询的顶部(个人偏好)。最终查询如下所示:
SELECT @total_signups := FORMAT(SUM(Signups), 0)
FROM
(
SELECT
"Country1" AS Country,
count(id) AS Signups
FROM source1.users
UNION SELECT
"Country2" AS Country,
count(id) AS Signups
FROM source2.users
...
UNION SELECT
"CountryN" AS Country,
count(id) AS Signups
FROM sourceN.st_users
) AS total_calc;
SELECT
"GRAND TOTAL" AS Country,
@total_signups AS Signups
UNION SELECT
Country,
FORMAT(Signups, 0) AS Signups
FROM
(
SELECT
"Country1" AS Country,
count(id) AS Signups
FROM source1.users
UNION SELECT
"Country2" AS Country,
count(id) AS Signups
FROM source2.users
...
UNION SELECT
"CountryN" AS Country,
count(id) AS Signups
FROM sourceN.st_users
ORDER BY Signups DESC
) AS all_signups;
这是一个查询的野兽,但它完成了工作!作为参考,我们使用的是 MySQL 5.7。
推荐阅读
- c++ - 如何从文本文件一次读取一个字符
- c# - Ms Bot 虚拟助手 bot 框架 V4 中的用户头像
- jmeter - jmeter 如何在不使用证书的情况下在 HTTPS 上工作
- python-3.x - 如何计算 h2o4gpu XGBClassifier 中的置信区间?
- java - 当更广泛的“for”循环循环返回时,更广泛的“for”循环内的嵌套“for”循环中的变量初始化是否会重新初始化变量?
- python - 尝试在我的 Mac OS (Catalina) 上安装 AWS CLI
- sql - SQL - 创建 SQL 以加入列表
- python - 如何加速 Google Drive API 搜索
- cloudkit - 为云套件远程推送通知定义订阅 ID
- flutter - List的过滤流