回答編集履歴
1
追記
test
CHANGED
@@ -39,3 +39,109 @@
|
|
39
39
|
group by dt;
|
40
40
|
|
41
41
|
```
|
42
|
+
|
43
|
+
|
44
|
+
|
45
|
+
# 追記
|
46
|
+
|
47
|
+
indicatorを別途マスター管理し、表示順を確定すればprocedureを利用できます
|
48
|
+
|
49
|
+
- 元テーブル
|
50
|
+
|
51
|
+
```SQL
|
52
|
+
|
53
|
+
create table daily_kpi(dt date,id int ,val int);
|
54
|
+
|
55
|
+
insert into daily_kpi values
|
56
|
+
|
57
|
+
('2017-01-01',1,1800),
|
58
|
+
|
59
|
+
('2017-01-01',2,500),
|
60
|
+
|
61
|
+
('2017-01-01',3,200),
|
62
|
+
|
63
|
+
('2017-01-02',1,2000),
|
64
|
+
|
65
|
+
('2017-01-02',2,700),
|
66
|
+
|
67
|
+
('2017-01-02',3,250);
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
create table indicator(id int primary key,name varchar(20));
|
72
|
+
|
73
|
+
insert into indicator values
|
74
|
+
|
75
|
+
(1,'impressions'),
|
76
|
+
|
77
|
+
(2,'sessions'),
|
78
|
+
|
79
|
+
(3,'users');
|
80
|
+
|
81
|
+
```
|
82
|
+
|
83
|
+
- procedure作成
|
84
|
+
|
85
|
+
```SQL
|
86
|
+
|
87
|
+
drop procedure if exists yokogaki;
|
88
|
+
|
89
|
+
delimiter //
|
90
|
+
|
91
|
+
create procedure yokogaki()
|
92
|
+
|
93
|
+
begin
|
94
|
+
|
95
|
+
declare a int;
|
96
|
+
|
97
|
+
declare b varchar(255);
|
98
|
+
|
99
|
+
declare done int default 0;
|
100
|
+
|
101
|
+
declare cur cursor for
|
102
|
+
|
103
|
+
select id,name from indicator order by id;
|
104
|
+
|
105
|
+
declare continue handler for sqlstate '02000' set done=1;
|
106
|
+
|
107
|
+
set @sql='select dt';
|
108
|
+
|
109
|
+
open cur;
|
110
|
+
|
111
|
+
repeat
|
112
|
+
|
113
|
+
fetch cur into a,b;
|
114
|
+
|
115
|
+
if not done then
|
116
|
+
|
117
|
+
set @sql=CONCAT(@sql,",sum(val*(id=",a,")) as ",b);
|
118
|
+
|
119
|
+
end if;
|
120
|
+
|
121
|
+
until done end repeat;
|
122
|
+
|
123
|
+
close cur;
|
124
|
+
|
125
|
+
set @sql=CONCAT(@sql," from daily_kpi group by dt order by id");
|
126
|
+
|
127
|
+
prepare stmt from @sql;
|
128
|
+
|
129
|
+
execute stmt;
|
130
|
+
|
131
|
+
end
|
132
|
+
|
133
|
+
//
|
134
|
+
|
135
|
+
delimiter ;
|
136
|
+
|
137
|
+
```
|
138
|
+
|
139
|
+
- 実行
|
140
|
+
|
141
|
+
```SQL
|
142
|
+
|
143
|
+
|
144
|
+
|
145
|
+
call yokogaki;
|
146
|
+
|
147
|
+
```
|