Sql server 从具有特定单词的列中提取数据的公共表表达式

Sql server 从具有特定单词的列中提取数据的公共表表达式,sql-server,common-table-expression,Sql Server,Common Table Expression,我有一个包含以下数据的临时表:col1是varchar,col2是int-identity 我需要编写一个CTE来从以task开头的列及其各自的startdate获取数据 这是我需要的输出: task startdate -------------------------------------------- task=call client 05062015 task=leave a msg 06062015

我有一个包含以下数据的临时表:col1是varchar,col2是int-identity

我需要编写一个CTE来从以task开头的列及其各自的startdate获取数据

这是我需要的输出:

task                       startdate
--------------------------------------------
task=call client           05062015
task=leave a msg           06062015
有人能帮我吗

到目前为止,我已经想到了这一点:

;with cte (txt) 
as 
( 
    select col1 from #temp where col1 like 'task%'
) 
select * from CTE 
到目前为止,它运行良好,我得到以下输出:

txt
---
task=call client 
task= leave a msg 
我一直在思考如何在CTE中实现startdate:

我写了以下查询:

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

您不需要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%'

当然,这假设每个task=。。。在col1中,紧接着是一条带有startdate的记录,按col2的顺序排列。

到目前为止您尝试了什么?请让我们看看你自己的努力,我已经想出了这个办法;使用cte txt作为select txt from temp where col1,如'task%'从cte中选择*直到这里它的工作良好im geitng下面的输出任务=调用客户机任务=留下一条消息im如何在cte中实现startdate我在下面的查询中写入startdate=substringcol1,11,20 from temp where col2>select top 1 col2 from temp where类似于“task%”的txt和类似于“%startdate%”的txt请不要将代码示例或示例数据放入注释中-因为您无法对其进行格式化,所以读取它非常困难。。。。取而代之的是:通过编辑你的问题来更新它,以提供额外的信息!谢谢。为什么有%startdate%startdate%还不够?如果col1后面没有带startdate的记录怎么办?那么您可能会收到此代码错误。当一个任务记录后面没有立即跟startdate记录时,您希望输出是什么?有些记录后面没有立即跟startdate,所需的输出保持不变任务记录和开始日期之间会有更多的任务记录吗?如何定义给定任务的开始日期?
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%'