回答編集履歴
1
追記
test
CHANGED
@@ -61,3 +61,71 @@
|
|
61
61
|
|
62
62
|
|
63
63
|
```
|
64
|
+
|
65
|
+
|
66
|
+
|
67
|
+
# 追記
|
68
|
+
|
69
|
+
UNIONでちがうカラム名のものを結合する場合、1行目のselectのカラム名が優先されます。
|
70
|
+
|
71
|
+
必要に応じて適当なエイリアスを振ってあげるとわかりやすくなるでしょう
|
72
|
+
|
73
|
+
```SQL
|
74
|
+
|
75
|
+
create table tbl1(ID varchar(10),Number1 int);
|
76
|
+
|
77
|
+
insert into tbl1 values
|
78
|
+
|
79
|
+
('田中',1),
|
80
|
+
|
81
|
+
('高橋',2),
|
82
|
+
|
83
|
+
('高橋',4),
|
84
|
+
|
85
|
+
('斉藤',1),
|
86
|
+
|
87
|
+
('斉藤',3),
|
88
|
+
|
89
|
+
('斉藤',3),
|
90
|
+
|
91
|
+
('斉藤',12);
|
92
|
+
|
93
|
+
|
94
|
+
|
95
|
+
create table tbl2(ID varchar(10),Number2 int);
|
96
|
+
|
97
|
+
insert into tbl2 values
|
98
|
+
|
99
|
+
('田中',3),
|
100
|
+
|
101
|
+
('林',2),
|
102
|
+
|
103
|
+
('林',12),
|
104
|
+
|
105
|
+
('林',12);
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
|
110
|
+
|
111
|
+
select ID
|
112
|
+
|
113
|
+
,sum(case Number when 1 then 1 else 0 end) as countOf_1
|
114
|
+
|
115
|
+
,sum(case Number when 2 then 1 else 0 end) as countOf_2
|
116
|
+
|
117
|
+
,sum(case Number when 3 then 1 else 0 end) as countOf_3
|
118
|
+
|
119
|
+
,sum(case Number when 12 then 1 else 0 end) as countOf_4
|
120
|
+
|
121
|
+
from(
|
122
|
+
|
123
|
+
select ID,Number1 as Number from tbl1 where Number1 in (1,2,3)
|
124
|
+
|
125
|
+
union all select ID,Number2 from tbl2 where Number2 =12
|
126
|
+
|
127
|
+
) as t1
|
128
|
+
|
129
|
+
group by ID;
|
130
|
+
|
131
|
+
```
|