码迷,mamicode.com
首页 > 数据库 > 详细

sqlServer拼结列字符串

时间:2018-08-11 13:00:04      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:tin   bsp   replace   code   tab   union all   null   with   order by   

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拼结列字符串

标签:tin   bsp   replace   code   tab   union all   null   with   order by   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!