gpt4 book ai didi

MySQL 在一个 SELECT 中获取不同 GROUP BY 上的 COUNT 和 SUM

转载 作者:行者123 更新时间:2023-11-29 01:40:32 42 4
gpt4 key购买 nike

我需要从看起来与此有关的表中选择数据:

monthStart  monthEnd newPhones totalPhones oblid
1 1 1 2 1
2 2 1 2 2
1 2 2 2 3
2 2 1 1 4
2 3 0 3 5

所以我想选择 4 个字段:月份,在 monthStart 的基础上计算月份的 obj,在 monthEnd 的基础上计算 newPhones 的总和,在 monthEnd 的基础上计算 totalPhones 的总和。

所以对于这个数据我需要选择这个:

month  count  totalPhones newPhones
1 3 2 1
2 2 5 4
3 0 3 0

计数第 1 个月 = 3,因为我们有 3 行 monthStart = 1,但我们只有一行monthEnd = 1,所以 1 个月的 totalPhones = 2,newPhones = 1计数 3d month = 0 因为我们有 0 行 monthStart = 3,但是我们有 3 个 totalPhones 和 0 个 newPhones for monthEnd = 3 - 我们应该显示这些数据。

我一直坚持这个。我试图从这个选择的结果中选择:

SELECT
monthStart,
monthEnd,
count(1) as uploaded,
sum(newPhones) as newPhones,
sum(totalPhones) as totalPhones
from TestGB
group by monthEnd, monthStart

但我得不到理想的结果。感谢您的帮助!

最佳答案

因此,如果有足够的数据来表示所有月份,我认为 StevieG 的答案是有效的。对于较小的数据集,如给定的样本数据,其中第 3 个月在月末但不在月开始,那么就会出现问题。然后你需要一些东西来确保所有的月份都被代表,我用 c 做的,合并只是为了让事情变得漂亮。

SELECT 
c.month,
coalesce(a.mycount,0),
coalesce(b.totalPhones,0),
coalesce(b.newphones,0)
FROM
(SELECT monthStart as month FROM TestGB
UNION
SELECT monthEnd as month FROM TestGB) c
LEFT OUTER JOIN
(SELECT
monthStart as month,
count(distinct obild) as mycount,
from TestGB
group by monthStart) a on a.month = c.month
LEFT OUTER JOIN
(SELECT
monthStart as month,
sum(newPhones) as newPhones,
sum(totalPhones) as totalPhones
from TestGB
group by monthEnd) b ON b.month = c.month

关于MySQL 在一个 SELECT 中获取不同 GROUP BY 上的 COUNT 和 SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25061171/

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