我有一个独特的情况,我需要根据2组连接行。另一个技巧是连接必须能够显示项目符号并添加换行符。这就是我的业务所要求的。我还应该添加最终目的地将是Excel。我已经使用具有项目符号和换行符的数据测试了使用SSIS导出到Excel,这个部分确实有效。
如何前往:
NodeIf
要:
pk orgnl_pk type text
1 1 one • Line One
2 1 one • Line Two
3 1 one • Line Three
4 1 two • Line One
7 3 one • Line One
8 3 two • Line One
9 3 two • Line Two
答案 0 :(得分:1)
正如Lamak指出的那样,最好留给表示层,但是如果你现在必须在sql中这样做...那么这将使用stuff()
with select ... for xml path ('')
method of string concatenation。
select
orgnl_pk
, [type]
, [text]=stuff(
(
select char(10) +i.[text]
from t as i
where i.orgnl_pk = t.orgnl_pk
and i.[type]=t.[type]
order by i.pk
for xml path (''), type).value('.','nvarchar(max)')
,1,0,'')
from t
group by orgnl_pk, [type]
rextester演示:http://rextester.com/GPFIMO37322
返回:
+----------+------+--------------+
| orgnl_pk | type | text |
+----------+------+--------------+
| 1 | one | • Line One |
| | | • Line Two |
| | | • Line Three |
| 1 | two | • Line One |
| 3 | one | • Line One |
| 3 | two | • Line One |
| | | • Line Two |
+----------+------+--------------+
<小时/> 更新字符(0x0007):
select
orgnl_pk
, [type]
, [text]=replace(stuff(
(
select char(10)+replace(i.[text],nchar(0x0007),'$BEL$')
from t as i
where i.orgnl_pk = t.orgnl_pk
and i.[type]=t.[type]
order by i.pk
for xml path (''), type).value('.','nvarchar(max)')
,1,1,''),'$BEL$',nchar(0x0007))
from t
group by orgnl_pk, [type]