首页 > 数据库技术 > 详细

sqlServer拼结列字符串

时间:2018-08-11 12:50:00      阅读:202      评论:0      收藏:0      [点我收藏+]

with table1(sessionID,message,createTime)
as
(
select 1 ,‘hello‘ ,‘2014/5/6‘ union all
select 1 ,‘word‘ ,‘2015/6/5‘ union all
select 1 ,‘你好‘ ,‘2015/7/4‘ union all
select 2 ,‘hello‘ ,‘同上时间‘ union all
select 2 ,‘你好‘ ,‘同上时间‘
)
select sessionID,
replace(cast((select ‘,‘+message from table1 t2
where t1.sessionID = t2.sessionID
for xml path(‘‘)) as varchar(100)),‘,‘,‘‘) as message,
max(createtime) createtime
from table1 t1
group by sessionID;

 

WITH t AS (SELECT sec,orgCode, TYPE,
replace(cast((select ‘,‘+sec from Columntype t2
 where t1.orgCode = t2.orgCode AND t1.type=t2.type
 for xml path(‘‘)) as varchar(100)),‘,‘,‘&‘) as ColumnCode
FROM Columntype t1
  WHERE ISNULL(sec,‘‘)<>‘‘ GROUP BY TYPE,orgCode,sec
 ),
 tr AS ( SELECT orgCode, TYPE, ColumnCode, RIGHT(ColumnCode,LEN(ColumnCode)-1) AS trs FROM t
 ),
 ty AS ( SELECT DISTINCT TYPE,orgCode,trs FROM tr
 ),
 tu AS (SELECT DISTINCT t.*,ct.orgname,ct.typeOrgCode FROM ty t LEFT JOIN Columntype ct ON t.orgCode=ct.orgCode
  WHERE t.orgCode=ct.orgCode AND t.type=ct.type
 )
 SELECT trs,typeOrgCode,tu.orgname FROM tu WHERE TYPE=‘dept‘ ORDER BY tu.orgnam

sqlServer拼结列字符串

原文:https://www.cnblogs.com/furenjian/p/9459374.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!