我有两列来自我的SQL查询 - 月,值,即值按月来临。我的要求是在3个月的时间内将这些月份分成几个月......并且值应该是这3个月的平均值。 例如,我有以下数据 -
Month Values
Mar-14 50
Apr-14 51
May-14 52
Jun-14 53
Jul-14 54
Aug-14 55
Sep-14 56
Oct-14 57
Nov-14 58
Dec-14 59
Jan-15 60
Feb-15 61
Mar-15 62
Apr-15 63
May-15 64
Jun-15 65
Jul-15 66
Aug-15 67
Sep-15 68
Oct-15 69
Nov-15 70
Dec-15 71
Jan-16 72
Feb-16 73
Mar-16 74
Apr-16 75
May-16 76
Jun-16 77
Jul-16 78
Aug-16 79
Sep-16 80
Oct-16 81
Nov-16 82
Dec-16 83
Jan-17 84
Feb-17 85
Mar-17 86
如何在MySql-
中实现以下输出3 Months Clubing Avg of Values
Mar-14 51
Jun-14 54
Sep-14 57
Dec-14 60
Mar-15 63
Jun-15 66
Sep-15 69
Dec-15 72
Mar-16 75
Jun-16 78
Sep-16 81
先谢谢
答案 0 :(得分:0)
有点乱,但你可以使用变量 - 假设你有一个递增的id列(或者你可以订购的东西)
drop table if exists t;
create table t(id int auto_increment primary key,Month varchar(10), Valus int);
insert into t (month,valus) values
('Mar-14', 50),
('Apr-14', 51),
('May-14', 52),
('Jun-14', 53),
('Jul-14', 54),
('Aug-14', 55),
('Sep-14', 56),
('Oct-14', 57),
('Nov-14', 58),
('Dec-14', 59);
select id,mth,rt
from
(
select id,month,valus,
@count:=@count+1 counter,
if(@count=1,@mth:=month,@mth:=@mth) mth,
if(@count=1,@block:=@block+1,@block:=@block) block,
if(@count<3,@sum:=@sum+valus,@sum:=(@sum+valus) / 3) rt,
if(@count=3,@count:=0,@count:=@count) creset,
if(@count=0,@sum:=0,@sum:=@sum) sumreset
from t
cross join (select @m ='',@count:=0,@sum:=0,@block:=0,@mth:='') s
order by id
)t
where counter = 3;
+----+--------+------+
| id | mth | rt |
+----+--------+------+
| 3 | Mar-14 | 51 |
| 6 | Jun-14 | 54 |
| 9 | Sep-14 | 57 |
+----+--------+------+
3 rows in set (0.03 sec)
稍微不那么凌乱但是使用sql的avg函数并使用变量填充3个月块中的第一个月
select block,mth,avg(valus)
from
(
select id,month,valus,
@count:=@count+1 counter,
if(@count=1,@mth:=month,@mth:=@mth) mth,
if(@count=1,@block:=@block+1,@block:=@block) block,
if(@count=3,@count:=0,@count:=@count) creset
from t
cross join (select @block:=0,@count:=0,@mth:='') s
order by id
) t
group by block,mth
order by block,mth
+-------+--------+------------+
| block | mth | avg(valus) |
+-------+--------+------------+
| 1 | Mar-14 | 51.0000 |
| 2 | Jun-14 | 54.0000 |
| 3 | Sep-14 | 57.0000 |
| 4 | Dec-14 | 59.0000 |
+-------+--------+------------+
4 rows in set (0.05 sec)
答案 1 :(得分:-1)
试试这个
create temporary table tab (month1 varchar(30), id int);
insert into tab (month1,id)
values('Mar-14' ,50),
('Apr-14' ,51),
('May-14' ,52),
('Jun-14' ,53),
('Jul-14' ,54),
('Aug-14' ,55),
('Sep-14' ,56),
('Oct-14' ,57),
('Nov-14' ,58),
('Dec-14' ,59),
('Jan-15' ,60),
('Feb-15' ,61),
('Mar-14' ,62);
set @row_number = 0;
select *
from tab where (@row_number := @row_number+1)%3= 1;
<强>结果强>
month1 id
'Mar-14' '50'
'Jun-14' '53'
'Sep-14' '56'
'Dec-14' '59'
'Mar-14' '62'