输入:
insert into example (fileno,type_cd,date_tm,be_nm) values('1','mismatch','match','mismatch');
insert into example (fileno,type_cd,date_tm,be_nm) values('2','match','mismatch','mismatch');
insert into example (fileno,type_cd,date_tm,be_nm) values('3','match','mismatch','match');
insert into example (fileno,type_cd,date_tm,be_nm) values('4','match','mismatch','mismatch');
答案 0 :(得分:2)
您可以取消设置初始数据:
select *
from example
unpivot (match for column_name in
(type_cd as 'type_cd', date_tm as 'date_tm', be_nm as 'be_nm'));
FILENO COLUMN_ MATCH
---------- ------- --------
1 type_cd mismatch
1 date_tm match
1 be_nm mismatch
2 type_cd match
2 date_tm mismatch
2 be_nm mismatch
...
然后将其旋转:
select *
from (
select column_name, match
from example
unpivot (match for column_name in
(type_cd as 'type_cd', date_tm as 'date_tm', be_nm as 'be_nm'))
)
pivot (count(*) for (match) in ('match' as match, 'mismatch' as mismatch));
COLUMN_NAME MATCH MISMATCH
----------- ---------- ----------
type_cd 3 2
date_tm 1 4
be_nm 2 3
或者稍微减少打字,但也许也不太清楚:
select *
from (select type_cd, date_tm, be_nm from example)
unpivot (match for column_name in
(type_cd as 'type_cd', date_tm as 'date_tm', be_nm as 'be_nm'))
pivot (count(*) for (match) in ('match' as match, 'mismatch' as mismatch));
COLUMN_NAME MATCH MISMATCH
----------- ---------- ----------
type_cd 3 2
date_tm 1 4
be_nm 2 3
我假设您在输入中错过了5 /错配/错配/匹配的行,因为没有它,您将不会获得这些总数。
或者有一种蛮力的方法,它涉及条件聚集并将多个查询的结果结合在一起,这需要多次击中表:
select 'type_cd' as column_name,
count(case when type_cd = 'match' then 1 end) as match,
count(case when type_cd = 'mismatch' then 1 end) as mismatch
from example
union all
select 'date_tm' as column_name,
count(case when date_tm = 'match' then 1 end) as match,
count(case when date_tm = 'mismatch' then 1 end) as mismatch
from example
union all
select 'be_nm' as column_name,
count(case when be_nm = 'match' then 1 end) as match,
count(case when be_nm = 'mismatch' then 1 end) as mismatch
from example;
COLUMN_NAME MATCH MISMATCH
----------- ---------- ----------
type_cd 3 2
date_tm 1 4
be_nm 2 3
无论是性能还是可维护性,unpivot / pivot方法都可以更好地扩展。