按顺序匹配sql查询

时间:2017-06-19 17:41:48

标签: sql sql-server window-functions rank

我有一张桌子A

col1 col2
1    81,123
2    90,99,100
3    4

和表2

col1  col2
1     23
1     123
2     90
3     4

我想在第一个匹配序列

上加入两个表

例如:

对于col1值= 1:23不匹配81或123因此它将移动到下一个,即123. 123匹配,所以它是答案

最终输出

col1   col2
1      123
2      90
3      4

我的查询是:

 select * from
(
select t1.col1,t2.col2,
ROW_NUMBER() over (partition by t1.col1 order by t1.col1) as dupRow 
from @table1 t1 inner join @table2 t2 on t1.col1=t2.col1
)a 
where a.duprow =1

2 个答案:

答案 0 :(得分:1)

只是为了好玩,试一试:

;with cteA as 
(
    select a.col1, split.a.value('.', 'varchar(100)') as string  
    from  (select col1, cast ('<m>' + replace(col2, ',', '</m><m>') + '</m>' as xml) as string from  a) as a cross apply string.nodes ('/m') as split(a)
) 
select a.col1, a.string as col2
from cteA a join b as b on a.col1 = b.col1 and a.string = b.col2

不确定它是否适用于所有情况,需要进行一些测试。 您可以在此处找到此代码的demo

  

编辑:

这将为您提供始终只有一个匹配,第一个(随机),每个col1

;with cteA as 
(
    select a.col1, split.a.value('.', 'varchar(100)') as string  
    from  (select col1, cast ('<m>' + replace(col2, ',', '</m><m>') + '</m>' as xml) as string from  a) as a cross apply string.nodes ('/m') as split(a)
) 
select col1, col2
from
(
    select a.col1, a.string as col2, ROW_NUMBER() over(partition by a.col1 order by a.col1) as nr
    from cteA a join b as b on a.col1 = b.col1 and a.string = b.col2
) t 
where nr = 1 

我写了另一段代码here作为演示。 如果连接条件满足两次,我写的第一个代码会给你多行。

答案 1 :(得分:1)

    SELECT COL1, COL2 FROM
(SELECT B.*, ROW_NUMBER() over (partition by B.COL1 order by B.COL1) AS DUPROW
FROM TABLEA A INNER JOIN TABLEB B ON A.COL1 = B.COL1
AND B.COL2 IN (SELECT * FROM SPLIT(A.COL2))
) R
WHERE DUPROW = 1

    --funtion to split comma seperated varchar to table
    CREATE FUNCTION [dbo].[Split] ( @strString varchar(4000))
    RETURNS  @Result TABLE(Value BIGINT)
    AS
    BEGIN

          DECLARE @x XML 
          SELECT @x = CAST('<A>'+ REPLACE(@strString,',','</A><A>')+ '</A>' AS XML)     
    INSERT INTO @Result            
    SELECT t.value('.', 'int') AS inVal
    FROM @x.nodes('/A') AS x(t)
        RETURN
    END