Mysql 我可以为该查询合并单独的月份和年份列吗?
我目前正在尝试跟踪每月发送的邮件数量,以及与一年前相比的卷变化百分比Mysql 我可以为该查询合并单独的月份和年份列吗?,mysql,sql,Mysql,Sql,我目前正在尝试跟踪每月发送的邮件数量,以及与一年前相比的卷变化百分比 以下是我当前的查询: Select a.mo, a.ye, a.Messages, ((a.Messages - b.Messages) / b.Messages) as "% Change" from( select MONTH(post_date) as mo, count(*) as "Mess
以下是我当前的查询:
Select
a.mo,
a.ye,
a.Messages,
((a.Messages - b.Messages) / b.Messages) as "% Change"
from(
select
MONTH(post_date) as mo,
count(*) as "Messages",
YEAR(post_date) as ye
from
pm_messages
WHERE
post_date > "2018-01-01 00:00:00"
group by
year(post_date),
month(post_date)
) a
left join (
select
MONTH(post_date) as mo,
YEAR(post_date) as ye,
count(*) as "Messages"
from
pm_messages
group by
year(post_date),
month(post_date)
) b on a.mo = b.mo
and a.ye -1 = b.ye
这非常有效,但是,它将月份和年份分别放在不同的列中,这会弄乱我正在处理的图表。但是,当我尝试将月份和年份拉入一列时,就像我在同一个表的其他查询中所做的那样,即使用:
SELECT DATE_FORMAT(`post_date`,'%M %Y')
我的查询不起作用 有人知道我如何结合当前查询,仍然计算前一年的回报率,但将月份和日期作为一列显示,而不是(月|年|消息|%Change) 谢谢!!
您可以使用
提取
代替单独的年()和月()函数:
EXTRACT(YEAR_MONTH from post_date)
当然,你必须按此分组,而不是按年、月分组。例如:
select
EXTRACT(YEAR_MONTH from post_date) yearmonth,
count(*) as "Messages"
from
pm_messages
group by
EXTRACT(YEAR_MONTH from post_date)
如果您有每月的数据,可以使用
lag()
:
请提供示例数据和所需结果。我建议发布一些示例数据(如创建表格+插入,足够5-10行)和此数据的所需结果(带说明)。看起来最终的查询比当前的查询更简单。@GordonLinoff我已经更新了帖子,以显示数据库和当前结果。我试图让它的最终结果与现在显示的完全一致,除了月份和年份合并在一列中,即2018年1月,或者如果可能的话,甚至2018年1月。谢谢@Akina我已经更新了帖子,以显示数据库和当前结果。我试图让它的最终结果与现在显示的完全一致,除了月份和年份合并在一列中,即2018年1月,或者如果可能的话,甚至2018年1月。谢谢我问过关于创建表+插入脚本的问题。你认为你的照片对你的数据复制有用吗?我可以从他们那里复制粘贴结构和数据吗?谢谢!唯一的问题是,这是否与使用“-1”来获取一年前的数据兼容?@Akina是的,谢谢
select year(post_date) as ye, month(post_date) as mo,
count(*) as Messages,
lag(count(*)) over (partition by month(post_date) order by year(post_date)) as prev_year
from pm_messages
where post_date >= '2018-01-01'
group by year(post_date), month(post_date)