前提・実現したいこと
現在のデータベース
id | user_id | name |
---|---|---|
1 | 1 | サッカー |
2 | 1 | 野球 |
3 | 1 | 陸上 |
4 | 2 | 野球 |
5 | 2 | 水泳 |
6 | 3 | テニス |
7 | 4 | 野球 |
8 | 4 | 陸上 |
まとめたいデータベース
user_id | name1 | name2 | name3 |
---|---|---|---|
1 | サッカー | 野球 | 陸上 |
2 | 野球 | 水泳 | |
3 | テニス | ||
4 | 野球 | 陸上 |
発生している問題・エラーメッセージ
[42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(partition by user_id) as seq from sample_table ) tmp group ...
https://dev.classmethod.jp/etc/sql-data-horizontal-vertical/
上記のURLより横にデータを変更する方法を見つけました。
しかし、 ,row_number() over (partition by employee_id) as seq
でsyntax
が出ました。
それと上記のURLのものでは横のカラムが固定のもの(qualification_id1~4)になってしまうためそのままでは使用できませんでした。
自分のものではname
のカラムは動的にしたいです。
ユーザーが持っているnameの数だけname(n)
のように増やしたいです。
該当のソースコード
mysql
1 2select 3 tmp.user_id, 4 max(case tmp.seq 5 when 1 6 then tmp.name 7 else null end) as name1, 8 max(case tmp.seq 9 when 2 10 then tmp.name 11 else null end) as name2, 12 max(case tmp.seq 13 when 3 14 then tmp.name 15 else null end) as name3, 16 max(case tmp.seq 17 when 4 18 then tmp.name 19 else null end) as name4 20from 21 ( 22 select 23 user_id, 24 name, 25 row_number() over (partition by user_id) as seq 26 from 27 sample_table 28 ) tmp 29group by 30 tmp.user_id; 31
放り投げの質問になってしまって申し訳ありませんが、ご教授、ご対応できる方がいましたら急ぎではありませんのでご対応していただけるとありがたいです。よろしくお願いいたします。
###追記(2019/05/04)
userテーブル
id | age | user_name | zip | address |
---|---|---|---|---|
1 | 10 | 斎藤 | 111-1111 | 東京都サンプル区サンプル1-1-1 |
2 | 11 | 近藤 | 111-1111 | 東京都サンプル区サンプル1-1-1 |
3 | 12 | 大久保 | 111-1111 | 東京都サンプル区サンプル1-1-1 |
4 | 23 | 中田 | 111-1111 | 東京都サンプル区サンプル1-1-1 |
sampleテーブル
id | user_id | name |
---|---|---|
1 | 1 | サッカー |
2 | 1 | 野球 |
3 | 1 | 陸上 |
4 | 2 | 野球 |
5 | 2 | 水泳 |
6 | 3 | テニス |
7 | 4 | 野球 |
8 | 4 | 陸上 |
csvでの出力
id | age | user_name | zip | address | name1 | name2 | name3 |
---|---|---|---|---|---|---|---|
1 | 10 | 斎藤 | 111-1111 | 東京都サンプル区サンプル1-1-1 | サッカー | 野球 | 陸上 |
2 | 11 | 近藤 | 111-1111 | 東京都サンプル区サンプル1-1-1 | 野球 | 水泳 | |
3 | 12 | 大久保 | 111-1111 | 東京都サンプル区サンプル1-1-1 | テニス | ||
4 | 23 | 中田 | 111-1111 | 東京都サンプル区サンプル1-1-1 | 野球 | 陸上 |
laravelで上記のようにcsvを出力させたいです。ご教授お願いいたします。
php
1 //ヘッダーを作成 2 $headers = ['id', 'age', 'user_name', 'zip', 'address']; 3 foreach ($headers as $header) { 4 $arr[0][] = $header; 5 } 6 7 //BODYを作成 8 $items = User::select('*')->get(); 9 foreach ($items as $key => $item) { 10 $arr[$key + 1] = $item; 11 } 12 13 $fp = fopen('file.csv', 'w'); 14 15 foreach ($arr as $fields) { 16 fputcsv($fp, $fields); 17 } 18 19 fclose($fp);
上記で出力されるcsv
id | age | user_name | zip | address |
---|---|---|---|---|
1 | 10 | 斎藤 | 111-1111 | 東京都サンプル区サンプル1-1-1 |
2 | 11 | 近藤 | 111-1111 | 東京都サンプル区サンプル1-1-1 |
3 | 12 | 大久保 | 111-1111 | 東京都サンプル区サンプル1-1-1 |
4 | 23 | 中田 | 111-1111 | 東京都サンプル区サンプル1-1-1 |

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/04 23:24
退会済みユーザー
2019/05/05 01:42