반응형
/*******************************************************************************************************************
-- 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', 2200001000005, 1, 'EE' union all select 'JP', 2200001000005, 2, 'DD' union all select 'JP', 2200081001803, 1, 'SS' union all select 'JP', 2200081001803, 2, NULL union all select 'JP', 2200081001803, 3, 'DD' union all select 'CN', 6588001000073, 1, NULL union all select 'CN', 6588001000073, 2, NULL union all select 'CN', 6716858000047, 1, 'AA' union all select 'CN', 6716858000047, 2, 'DD' union all select 'CN', 6716858000047, 3, NULL; 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 |
반응형