DDL:
drop table tblx;
create table tblx
(
seq int,
col2 varchar(50),
xyzid int,
bid int,
col3 varchar(50),
col4 varchar(50)
);
データ:
insert into tblx(seq,col2,xyzid,bid,col3,col4) values
(1, 'foo' , 1, 1, '12', 'wqw'),
(3, 'bar' , 1, 10, '77', 'kikk'),
(2, 'foobar' , 1, 2, 'w', 'ed'),
(1, 'barfoo' , 2, 4, 'e', 'dwe'),
(2, 'asdsad' , 2, 5, 'e', 'e');
CTEアプローチの使用:
with a(xyzid, seq, x) as
(
select xyzid, seq, cast(col2 + '-' + col3 + '-' + col4 as varchar(max)) as x
from tblx
where seq = 1
union all
select t.xyzid, t.seq, a.x + '#' + (t.col2 + '-' + t.col3 + '-' + t.col4)
from tblx t
join a on a.xyzid = t.xyzid and t.seq = a.seq + 1
)
select xyzid, rtrim(x) as x
from a w
where seq = (select MAX(seq) from a where xyzid = w.xyzid)
order by xyzid;
出力:
xyzid x
----------- -----------------------------------
1 foo-12-wqw#foobar-w-ed#bar-77-kikk
2 barfoo-e-dwe#asdsad-e-e
(2 row(s) affected)
メインテーブル(テーブルAなど)を使用するには、クエリを簡単に変更する必要があります。
with a(xyzid, seq, x) as
(
select xyzid, seq, cast(col2 + '-' + col3 + '-' + col4 as varchar(max)) as x
from tblx
where seq = 1
union all
select t.xyzid, t.seq, a.x + '#' + (col2 + '-' + col3 + '-' + col4)
from tblx t
join a on a.xyzid = t.xyzid and t.seq = a.seq + 1
)
select w.xyzid, rtrim(x) as x
from tblA w -- just add this main table
left join a on a.xyzid = w.xyzid
and seq = (select MAX(seq) from a where xyzid = w.xyzid)
order by xyzid;
データ:
create table tblA
(
aid int identity(1,1) primary key,
col2 varchar(50),
col3 varchar(50),
xyzid int
);
insert into tblA(col2,col3,xyzid) values
('','',1),
('','',2),
('','',3);
出力:
xyzid x
----------- ------------------------------------
1 foo-12-wqw#foobar-w-ed#bar-77-kikk
2 barfoo-e-dwe#asdsad-e-e
3 NULL
(3 row(s) affected)
seqフィールドが連続していない、および/または一意でない場合は、シーケンサーを配置します。
with sequencer as
(
select
xyzid, ROW_NUMBER() over(partition by xyzid order by seq) as seq
, col2, col3, col4
from tblx
)
,a(xyzid, seq, x) as
(
select xyzid, seq, cast(col2 + '-' + col3 + '-' + col4 as varchar(max)) as x
from sequencer
where seq = 1
union all
select t.xyzid, t.seq, a.x + '#' + (col2 + '-' + col3 + '-' + col4)
from sequencer t
join a on a.xyzid = t.xyzid and t.seq = a.seq + 1
)
select w.xyzid, rtrim(x) as x
from tblA w
left join a on a.xyzid = w.xyzid
and seq = (select MAX(seq) from a where xyzid = w.xyzid)
order by xyzid;
非連続シーケンスのサンプル:
insert into tblx(seq,col2,xyzid,bid,col3,col4) values
(1, 'foo' , 1, 1, '12', 'wqw'),
(5, 'bar' , 1, 10, '77', 'kikk'),
(3, 'foobar' , 1, 2, 'w', 'ed'),
(1, 'barfoo' , 2, 4, 'e', 'dwe'),
(3, 'asdsad' , 2, 5, 'e', 'e');
出力(同じ):
xyzid x
----------- --------------------------------------
1 foo-12-wqw#foobar-w-ed#bar-77-kikk
2 barfoo-e-dwe#asdsad-e-e
3 NULL
(3 row(s) affected)
速度に関しては、まだ速いです。CTEクエリのコストはXMLアプローチに対して5%であり、95%です。