これらの例は、SQL Server 2012の
declare @T table (id int identity(1,1), email1 varchar(80), email2 varchar(80), email3 varchar(80), email4 varchar(80));
insert into @T (email1,email2,email3,email4) values
('[email protected]','[email protected]','[email protected]','[email protected]'),
('[email protected]',null,'[email protected]',null),
('[email protected]','[email protected]','[email protected]','[email protected]');
select id,
concat(
max(case when n=1 then m end),
max(case when n=2 then ';'+m end),
max(case when n=3 then ';'+m end),
max(case when n=4 then ';'+m end)
) as emails
from
(
select id, n, m, sum(len(m)+1) over (partition by id order by n ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as RunningTotal
from @T t0
cross apply (values (1,email1),(2,email2),(3,email3),(4,email4)) mails(n,m)
) q
where RunningTotal <= 100
group by id;
またはXMLトリックを使用して動作します:
select id,
STUFF((select ';'+m
from
(
select m, sum(len(m)+1) over (partition by id order by n ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as RunningTotal
from @T t0
cross apply (values (1,email1),(2,email2),(3,email3),(4,email4)) q(n,m)
where t0.id = t.id
) q
where RunningTotal <= 100
FOR XML PATH ('')
),1,1,'') as mails
from @T t
group by id;
やケース、連結、左、CHARINDEXと逆を使用して(?少なくとも '醜いです') :
select id,
(case
when len(emails)>100
then left(left(emails,101-charindex(';',reverse(left(emails,101)))),100)
else emails
end) as emails
from (
select id, concat(email1,';'+email2,';'+email3,';'+email4) as emails
from @T
) q;
おそらくこれは?
select id,
concat(email1,
case when isnull(len(email1),0)+isnull(len(email2)+1,0) <= 100 then ';'+email2 end,
case when isnull(len(email1),0)+isnull(len(email2)+1,0)+isnull(len(email3)+1,0) <= 100 then ';'+email3 end,
case when isnull(len(email1),0)+isnull(len(email2)+1,0)+isnull(len(email3)+1,0)+isnull(len(email4)+1,0) <= 100 then ';'+email4 end
) as emails
from @T;
何rdbms? SQLサーバー? – SQLChao
SQL Server、はい。それが無効であれば、気にしていないようです。うまくいきます。 :)私はそれ以降のケースについては、MSのドキュメントからフォーマットを得ました。 –