回答編集履歴
1
tuiki
test
CHANGED
@@ -73,3 +73,73 @@
|
|
73
73
|
group by user
|
74
74
|
|
75
75
|
````
|
76
|
+
|
77
|
+
|
78
|
+
|
79
|
+
# 蛇足
|
80
|
+
|
81
|
+
これをmysqlでやるときprocedureでこう作っておきます
|
82
|
+
|
83
|
+
```SQL
|
84
|
+
|
85
|
+
drop procedure if exists shukei;
|
86
|
+
|
87
|
+
delimiter //
|
88
|
+
|
89
|
+
create procedure shukei(IN start_year int,IN end_year int)
|
90
|
+
|
91
|
+
begin
|
92
|
+
|
93
|
+
declare year int default 0;
|
94
|
+
|
95
|
+
set year=start_year;
|
96
|
+
|
97
|
+
set @sql='select user';
|
98
|
+
|
99
|
+
while year<=end_year do
|
100
|
+
|
101
|
+
set @sql=concat(@sql,',sum((year=',year,')*val) as x',year);
|
102
|
+
|
103
|
+
set year=year+1;
|
104
|
+
|
105
|
+
end while;
|
106
|
+
|
107
|
+
set @sql=concat(@sql,' from tbl group by user');
|
108
|
+
|
109
|
+
prepare stmt from @sql;
|
110
|
+
|
111
|
+
execute stmt;
|
112
|
+
|
113
|
+
end
|
114
|
+
|
115
|
+
//
|
116
|
+
|
117
|
+
delimiter ;
|
118
|
+
|
119
|
+
```
|
120
|
+
|
121
|
+
|
122
|
+
|
123
|
+
集計の呼び出し
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
```SQL
|
128
|
+
|
129
|
+
call shukei(2000,2003);
|
130
|
+
|
131
|
+
```
|
132
|
+
|
133
|
+
|
134
|
+
|
135
|
+
結果:
|
136
|
+
|
137
|
+
|user|x2000|x2001|x2002|x2003|
|
138
|
+
|
139
|
+
|:--:|--:|--:|--:|--:|
|
140
|
+
|
141
|
+
|AAA|3|7|65|56|
|
142
|
+
|
143
|
+
|BBB|54|4|42|4|
|
144
|
+
|
145
|
+
|CCC|5|86|31|21
|