gpt4 book ai didi

mysql - 多年mysql的动态列创建

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

我为 MYSQL 编写了以下查询:

SELECT DATE_FORMAT(start, '%m/%e') as start,  (@total := @total + T.id) AS TotalApps, DATE_FORMAT(start, '%Y') as year FROM (SELECT start,COUNT(*) AS id FROM application WHERE start LIKE '2016%' GROUP BY MONTH(start), DAY(start)) AS T, (SELECT @total:=0) AS n

它按预期输出表格,其中包含开始日期、累计申请数和年份的列:

current table

我想做的是删除 LIKE '2016%' 这样我就可以获得所有年份的数据并最终得到一个如下所示的表格:

desired table

等等。

最佳答案

该问题的累积性质使其与大多数其他关键问题大不相同。这是一种每年使用单独变量的方法:

SELECT DATE_FORMAT(start, '%m/%d') as mmdd, 
(@t2016 := @t2016 + sum(year(start) = 2016)) as tot_2016,
(@t2015 := @t2015 + sum(year(start) = 2015)) as tot_2015,
(@t2014 := @t2014 + sum(year(start) = 2014)) as tot_2014
FROM application a CROSS JOIN
(SELECT @t2016 := 0, @t2015 := 0, @t2014 := 0) params
GROUP BY DATE_FORMAT(start, '%m/%d')
ORDER BY mmdd;

编辑:

有时,group by 和变量不能一起工作。这是使用子查询修复的:

SELECT mmdd,
(@t2016 := @t2016 + cnt_2016) as tot_2016,
(@t2015 := @t2015 + cnt_2015) as tot_2015,
(@t2014 := @t2014 + cnt_2014) as tot_2014
FROM (SELECT DATE_FORMAT(start, '%m/%d') as mmdd,
sum(year(start) = 2016)) as cnt_2016,
sum(year(start) = 2015)) as cnt_2015,
sum(year(start) = 2014)) as cnt_2014
FROM application a
GROUP BY DATE_FORMAT(start, '%m/%d')
ORDER BY mmdd
) x CROSS JOIN
(SELECT @t2016 := 0, @t2015 := 0, @t2014 := 0) params;

关于mysql - 多年mysql的动态列创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36323219/

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