common table expression to fetch data from columns with particular word

时间:2015-05-07 06:45:54

标签: sql-server common-table-expression

I have a temp table with following data: col1 is a varchar and col2 is int identity

col1                       col2
------------------------------------
null                        1
null                        2
task=call client            3
startdate=05062015          4
a                           5
fgfg                        6
task=leave a msg            7
startdate=06062015          8

I need to write a CTE to fetch data from columns that begin with task , and their respective startdate

This is the output that I need:

task                       startdate
--------------------------------------------
task=call client           05062015
task=leave a msg           06062015

Can someone please help me with this ?

I have come up with this so far:

;with cte (txt) 
as 
( 
    select col1 from #temp where col1 like 'task%'
) 
select * from CTE 

So far it's working fine and I'm getting the below output:

txt
---
task=call client 
task= leave a msg 

I'm stuck with how to implement the startdate in the CTE:

I have written the below query:

startdate = substring(col1,11,20) 
from #temp 
where col2 > (select top 1 col2 
              from #temp 
              where col1 like 'task%' ) and col1 like '%startdate%'

1 个答案:

答案 0 :(得分:1)

您不需要CTE - 简单的连接就可以了:

SELECT T1.col1 AS [Task],
    SUBSTRING(T2.col1,10,8) AS [Startdate]
FROM
    #temp T1
INNER JOIN
    #temp T2 WHERE T1.col2 + 1 = T2.col2
WHERE
    T1.col1 like 'task%'

当然,这假设col1中带有“task = ...”的每条记录后面紧跟着一个带有startdate的记录,按col2顺序排列。