前提・実現したいこと
- MySQL5.6
ログテーブルの各codeについて出現位置(1〜4)ごとの出現回数と利用ユーザー数を集計し、集計テーブルの様な形に落とし込みたい
ログテーブル
|id|user_id|code1|code2|code3|code4|
|--|--|
|1|1|100001|100002|100003|100004|
|2|1|100003|100002|100005|100004|
|3|2|100004|100002|100003|100001|
|4|4|100004|100001|100003|100002|
|5|6|100005|100002|100003|100004|
|6|2|100001|100002|100003|100004|
sql
1CREATE TABLE `log` ( 2 `id` int(11) NOT NULL, 3 `user_id` int(11) DEFAULT NULL, 4 `code1` int(11) DEFAULT NULL, 5 `code2` int(11) DEFAULT NULL, 6 `code3` int(11) DEFAULT NULL, 7 `code4` int(11) DEFAULT NULL, 8 PRIMARY KEY (`id`) 9) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
(定義は簡略化してます)
集計テーブル
|code|first_count|first_user_count|second_count|second_user_count|third_count|third_user_count|fourth_count|fourth_user_count|
|--|--|
|100001|2|2|1|1|0|0|1|1|
|100002|0|0|5|3|0|0|1|1|
|100003|1|1|0|0|5|4|0|0|
|100004|2|2|0|0|0|0|4|3|
|100005|1|1|0|0|1|1|0|0|
sql
1CREATE TABLE `summary` ( 2 `code` int(11) NOT NULL, 3 `first_count` int(11) DEFAULT NULL, 4 `first_user_count` int(11) DEFAULT NULL, 5 `second_count` int(11) DEFAULT NULL, 6 `second_user_count` int(11) DEFAULT NULL, 7 `third_count` int(11) DEFAULT NULL, 8 `third_user_count` int(11) DEFAULT NULL, 9 `fourth_count` int(11) DEFAULT NULL, 10 `fourth_user_count` int(11) DEFAULT NULL, 11 PRIMARY KEY (`code`) 12) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 13
(定義は簡略化してます)
試したこと・困っていること
1−4それぞれに関しては下記の様なクエリを4つ書けば取れそうなのですが(3,4は省略)
これを1テーブルに落とし込むのに難儀しております。
最終的にはselect insertのような形にしたいと思っており、難しいようであればそれぞれselectしてスクリプトで処理するかなという感じではあるのですが何かいいアイディアはありませんでしょうか。
- 1番目に出現したデータの集計
sql
1SELECT 2 code1, 3 COUNT(*) as first_count, 4 COUNT(DISTINCT user_id) as first_user_count 5FROM 6 log 7GROUP BY code1;
|code|first_count|first_user_count|
|--|--|
|100001|2|2|
|100003|1|1|
|100004|2|2|
|100005|1|1|
- 2番目に出現したデータの集計
sql
1SELECT 2 code2, 3 COUNT(*) as second_count, 4 COUNT(DISTINCT user_id) as second_user_count 5FROM 6 log 7GROUP BY code2;
|code|second_count|second_user_count|
|--|--|
|100001|1|1|
|100002|5|3|
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。