gpt4 book ai didi

MySQL 如何在一个查询中返回 COUNT 总数以及使用 GROUP BY 的 COUNT

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

我有以下查询:

SELECT location, COUNT( location ) AS Total, (

SELECT location, COUNT( location ) AS Responses
FROM `trespondent`
WHERE completion_status IN ('Started', 'Complete')
GROUP BY location
)

FROM `trespondent`
GROUP BY location

这会返回一个错误:

Operand should contain 1 column(s)

这是完全正确的,因为会有不止一行。

我想要在单个查询中实现的目标是返回“位置”中每个选项的总数,然后返回“位置”中每个选项的“已开始”或“已完成”的数量.

如果可以在单个查询中实现这一点,请提供任何建议,如果可以,欢迎任何指点。

最佳答案

您可以使用 UNION 子句更改查询,如下所示,以使用两个版本的查询并获取总体结果

SELECT location, COUNT( location ) AS Total
FROM `trespondent`
GROUP BY location

UNION ALL

SELECT location, COUNT( location ) AS Responses
FROM `trespondent`
WHERE completion_status IN ('Started', 'Complete')
GROUP BY location

或者可能使用JOIN来连接两个查询结果,例如

SELECT t1.location as T1location, 
COUNT( t1.location ) AS Total,
tab.Responses,
tab.location as tablocation
FROM `trespondent` t1
JOIN
(
SELECT location, COUNT( location ) AS Responses
FROM `trespondent`
WHERE completion_status IN ('Started', 'Complete')
GROUP BY location
) tab
ON t1.location = tab.location
GROUP BY t1.location

关于MySQL 如何在一个查询中返回 COUNT 总数以及使用 GROUP BY 的 COUNT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26450680/

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