回答編集履歴
1
追記
answer
CHANGED
@@ -29,4 +29,38 @@
|
|
29
29
|
) as t1
|
30
30
|
group by ID
|
31
31
|
|
32
|
+
```
|
33
|
+
|
34
|
+
# 追記
|
35
|
+
UNIONでちがうカラム名のものを結合する場合、1行目のselectのカラム名が優先されます。
|
36
|
+
必要に応じて適当なエイリアスを振ってあげるとわかりやすくなるでしょう
|
37
|
+
```SQL
|
38
|
+
create table tbl1(ID varchar(10),Number1 int);
|
39
|
+
insert into tbl1 values
|
40
|
+
('田中',1),
|
41
|
+
('高橋',2),
|
42
|
+
('高橋',4),
|
43
|
+
('斉藤',1),
|
44
|
+
('斉藤',3),
|
45
|
+
('斉藤',3),
|
46
|
+
('斉藤',12);
|
47
|
+
|
48
|
+
create table tbl2(ID varchar(10),Number2 int);
|
49
|
+
insert into tbl2 values
|
50
|
+
('田中',3),
|
51
|
+
('林',2),
|
52
|
+
('林',12),
|
53
|
+
('林',12);
|
54
|
+
|
55
|
+
|
56
|
+
select ID
|
57
|
+
,sum(case Number when 1 then 1 else 0 end) as countOf_1
|
58
|
+
,sum(case Number when 2 then 1 else 0 end) as countOf_2
|
59
|
+
,sum(case Number when 3 then 1 else 0 end) as countOf_3
|
60
|
+
,sum(case Number when 12 then 1 else 0 end) as countOf_4
|
61
|
+
from(
|
62
|
+
select ID,Number1 as Number from tbl1 where Number1 in (1,2,3)
|
63
|
+
union all select ID,Number2 from tbl2 where Number2 =12
|
64
|
+
) as t1
|
65
|
+
group by ID;
|
32
66
|
```
|