sql - 拆分字符串以分隔列和删除值

时间:2018-01-03 20:36:41

标签: sql sql-server sql-server-2008

我有以下查询 -

<0 x 0 matrix>

它会返回如下结果:

select um.usrmst_name 'ITAM Owner',
       wg.workgrp_name 'TIDAL Workgroup',
       isnull(jm.jobmst_prntname, '') + '\' + jm.jobmst_name 'Job'
       from jobmst jm
inner join workgrp wg on wg.workgrp_id = jm.jobmst_owner
inner join usrmst um on um.usrmst_id = wg.workgrp_owner
where jm.jobmst_active = 'Y' and jm.jobmst_dirty != 'X' and um.usrmst_domain = 'ITAM'

我希望它看起来像这样:

| ITAM Owner | TIDAL Workgroup | Job
| CORE       | Sage-Talcura    | \Sage-Talcura
| CORE       | Sage-Talcura    | \Sage-Talcura\1.0 Import Sage-Talcura Data   

如何修改我的查询以实现此结果?我尝试过做一个案例以及一个左/右复杂的子串,我仍然无法让它(LEFT)工作:

| ITAM Owner | TIDAL Workgroup | Job Group     | Job
| CORE       | Sage-Talcura    | \Sage-Talcura | 1.0 Import Sage-Talcura Data   

2 个答案:

答案 0 :(得分:1)

case when CHARINDEX('\',Job,2)=0 then Job else left(Job,CHARINDEX('\',Job,2)-1) end 'Job Group',
case when CHARINDEX('\',Job,2)>1 then SUBSTRING(Job,CHARINDEX('\',Job,2)+1,999) end 'Job'

答案 1 :(得分:0)

请使用此.. GROUP BY和MAX。

select um.usrmst_name 'ITAM Owner',
       wg.workgrp_name 'TIDAL Workgroup',
       isnull(jm.jobmst_prntname, '') [Job Group],
       MAX(jm.jobmst_name) 'Job'
       from jobmst jm
inner join workgrp wg on wg.workgrp_id = jm.jobmst_owner
inner join usrmst um on um.usrmst_id = wg.workgrp_owner
where jm.jobmst_active = 'Y' and jm.jobmst_dirty != 'X' and um.usrmst_domain = 'ITAM'
GROUP BY um.usrmst_name, wg.workgrp_name ,isnull(jm.jobmst_prntname, '')