gpt4 book ai didi

mysql - 将 count(*) 与 SQL 语句合并到一张表中

转载 作者:行者123 更新时间:2023-11-29 06:11:50 24 4
gpt4 key购买 nike

我的 MySQL 数据库中有两个表(表 1 和表 2)。我想编写一个 SQL 查询,在格式良好的报告中输出一些摘要统计信息。

让我们举个例子,考虑第一个 SQL 查询,该查询从第一个表中获取 57 岁以上的用户

SELECT count(*) AS OlderThank57
FROM table1
WHERE age >57

从第二个表中,我们希望获得女性用户的数量

SELECT count(*) AS FemaleUsers
FROM table2
WHERE gender = "female"

现在我想要像下面这样的输出

Number of Felame users from table 2: 514
Number of users over the age of 57 from table 1: 918

生成此类报告的最佳方式是什么?

最佳答案

我愿意从阿德里安的答案中扩展一个级别...作为两个单独的字段返回,以便您可以将它们单独放置在报告中,或对齐/格式化数字等

SELECT 'Number of Female users from table 2:' as Msg, 
count(*) as Entries
FROM table1
WHERE age >57
UNION ALL
SELECT 'Number of users over the age of 57 from table 1:' as Msg,
count(*) as Entries
FROM table2
WHERE gender = "female"

您可能必须强制两个“Msg”列具有相同的填充长度,否则可能会被截断。再说一次,只是另一种选择...

关于mysql - 将 count(*) 与 SQL 语句合并到一张表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8749252/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com