반응형

/*******************************************************************************************************************
-- Title : [SQL2016] JSON을 활용한 String Merge하기 - dBRang
-- Reference : dBRang
-- Key word : for json auto 멀티값 싱글값 merge 멀티로우
*******************************************************************************************************************/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
use tempdb;
go
 
-- drop table #ttt;
create table #ttt
( db_cd varchar(10)
, skey bigint
, seq int
, code nvarchar(10)
);
 
insert into #ttt 
select 'JP'22000010000051'EE' union all
select 'JP'22000010000052'DD' union all
select 'JP'22000810018031'SS' union all
select 'JP'22000810018032NULL union all
select 'JP'22000810018033'DD' union all
select 'CN'65880010000731NULL union all
select 'CN'65880010000732NULL union all
select 'CN'67168580000471'AA' union all
select 'CN'67168580000472'DD' union all
select 'CN'67168580000473NULL;
 
select * from #ttt
 
-- Group By시 JSON을 통한 집계 처리
select db_cd, skey
     , js_code = (select code 
                  from #ttt 
                  where db_cd = a.db_cd and skey = a.skey
                  for json auto, include_null_values
                 )
from #ttt a
group by db_cd, skey;
 
 
-- ("|")구분자로 Merge
select db_cd, skey, js_code 
     , case when str_merge = '|' then NULL
            else str_merge
       end "str_merge_result"
from 
(
    select *
         , replace(replace(replace(replace(replace(replace(js_code
           , '},{','|'),'"code":',''),'null',''),'[{',''),'}]',''),'"',''"str_merge"
    from
    (
        select db_cd, skey
             , js_code = (select code 
                          from #ttt 
                          where db_cd = a.db_cd and skey = a.skey
                          for json auto, include_null_values
                         )
        from #ttt a
        group by db_cd, skey
    ) aa
) aaa
 
cs



반응형

+ Recent posts