按月和一年的小组多年
寻求帮助,我敢肯定是一个简单的新秀错误。在我的查询中逐函数的组没有区分不同的年份。所有年份的7月数据都包含在同一行中,而不是按月+年。我想念什么?
这是除函数组以外的其他疑问:
SELECT
`index`,
`month`,
`year`,
sum(maintained) as maintained,
sum(repaired) as repaired
FROM
(
SELECT
MONTH(`service_date`) AS 'index',
MONTHNAME(`service_date`) AS 'month',
YEAR(`service_date`) AS 'year',
COUNT(`service_date`) AS 'maintained',
0 AS repaired
FROM `service_log`
GROUP BY MONTH(`service_date`)
UNION
SELECT
MONTH(`service_date`) AS 'index',
MONTHNAME(`service_date`) AS 'month',
YEAR(`service_date`) AS 'year',
0 AS 'maintained',
COUNT(`other_repairs`) AS 'repaired'
FROM `service_log`
GROUP BY MONTH(`service_date`)
)
AS union_name
GROUP BY `year`,`month`
ORDER BY `year` DESC,`index` DESC
输出以这种形式:
每月 | 维修 | 26日30 |
---|---|---|
2022年7月 | 45日 | 45 |
6月45日2022 | 30 | 26 |
2022 2022 | 20 | 4月26日 |
2022年4月 | 19 | 19 |
Looking for help with what I'm sure is a simple rookie mistake. The GROUP BY function in my query is not distinguishing between different years. Data for July for all years are being included on the same row rather than by month+year. What am I missing?
This is the query that other than the GROUP BY function works properly:
SELECT
`index`,
`month`,
`year`,
sum(maintained) as maintained,
sum(repaired) as repaired
FROM
(
SELECT
MONTH(`service_date`) AS 'index',
MONTHNAME(`service_date`) AS 'month',
YEAR(`service_date`) AS 'year',
COUNT(`service_date`) AS 'maintained',
0 AS repaired
FROM `service_log`
GROUP BY MONTH(`service_date`)
UNION
SELECT
MONTH(`service_date`) AS 'index',
MONTHNAME(`service_date`) AS 'month',
YEAR(`service_date`) AS 'year',
0 AS 'maintained',
COUNT(`other_repairs`) AS 'repaired'
FROM `service_log`
GROUP BY MONTH(`service_date`)
)
AS union_name
GROUP BY `year`,`month`
ORDER BY `year` DESC,`index` DESC
The output is in this form:
Month | Maint | Repair |
---|---|---|
July 2022 | 80 | 45 |
June 2022 | 30 | 21 |
May 2022 | 20 | 26 |
April 2022 | 30 | 19 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论