退会しちゃったっぽいので備忘録
SQL
1create table user(user_id int primary key,name varchar(10));
2insert into user values
3(1,'山田太郎'),
4(2,'佐藤二郎');
5
6create table status(status_id int primary key,name varchar(10));
7insert into status values
8(1,'問い合わせ'),
9(2,'資料請求'),
10(3,'失注'),
11(4,'成約');
12
13create table user_status(user_id int,status_id int,amount int,unique key(user_id,status_id));
14insert into user_status values
15(1,1,4),
16(1,2,7),
17(1,3,12),
18(2,1,5),
19(2,3,2),
20(2,4,4);
21
22select t2.name as ユーザー,
23問い合わせ,
24資料請求,
25失注,
26成約
27from (select user_id
28,sum((status_id=1)*amount) as 問い合わせ
29,sum((status_id=2)*amount) as 資料請求
30,sum((status_id=3)*amount) as 失注
31,sum((status_id=4)*amount) as 成約
32from user_status
33group by user_id
34) as t1
35inner join user as t2 using(user_id)