在sql中修剪输出

时间:2014-10-02 03:48:56

标签: sql sql-server database

我有这个查询

 Select distinct 
    tag 
 from 
     (SELECT  *
      FROM [piarchive].[picomp2]
      WHERE tag like '%CPU_Active' 
        and time between '2014/10/01 10:13:08' and '2014/10/01 10:18:37'
        and value = -524289 
      order by time desc) as t1

有了这个我得到输出

RSV23.VMS_CPU01_1_0.CPU_Active

我需要将此输出修剪为

RSV23.VMS_CPU1_1_0

需要在不同的查询中使用此修剪输出,如下所示

 SELECT  *
 FROM [piarchive].[picomp2]
 WHERE tag like 'RSV23.VMS_CPU01_1_0%' and tag not like '%CPU_Active' and  time   
 between '2014/10/01 10:13:08'and'2014/10/01 10:18:37'  order by time desc

如何在第二次查询中首先修剪并使用该输出?

2 个答案:

答案 0 :(得分:0)

我得到了答案。

 SELECT top 6 *
 FROM [piarchive].[picomp2]
 WHERE tag like 
 (
   Select distinct left(tag,19) + '%' 
   from (SELECT  *
   FROM [piarchive].[picomp2]
   WHERE tag like '%CPU_Active' and  time between '2014/10/01 10:13:08'and'2014/10/01 10:18:37'
   and value=-524289 order by time desc) as t1
 )  
   and tag not like '%CPU_Active' and tag not like '%Program%' and time between '2014/10/01  
   10:13:08'and'2014/10/01 10:18:37'  order by time desc

答案 1 :(得分:0)

你应该在查询结果中找到dot(。)的最后一个索引,并在该索引之后删除字符串。

declare @result nvarchar(100)
set @result = (Select distinct tag from (SELECT  * FROM [piarchive].[picomp2] WHERE tag like '%CPU_Active' and time between '2014/10/01 10:13:08' and '2014/10/01 10:18:37' and value = -524289 order by time desc) as t1)

declare @LastIndex int 
set @LastIndex = len(@result) - charindex('.', reverse(@result))

substring(@result,0,@LastIndex) // this will give you the required result