SELECT rows with unique values in two columns

前端 未结 4 1721
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 08:48

I have a table like this:

id          col1 col2        
----------- ---- ----------- 
1           A    5
2           A    6
3           B    5
4           B          


        
4条回答
  •  攒了一身酷
    2020-12-22 09:14

    This is not an easy one to solve through straight SQL. I figured I'd give it a crack using a recursive CTE. This spits out all possible combinations, but... in one field called "path" here. Perhaps it will present a way forward using straight tsql.

    With recCTE AS
    (
        SELECT 
          col1, 
          col2, 
          0 as depth, 
          CAST(col1 + '|' + CAST(col2 AS varchar(10)) AS VARCHAR(30)) as path 
        FROM t
    
        UNION ALL
    
        SELECT       
          t1.col1, 
          t1.col2, 
          rec.depth + 1, 
          CAST(rec.path + '>' + t1.col1 + '|' + cast(t1.col2 as varchar(10)) as varchar(30))
        FROM t t1
            INNER JOIN recCTE rec
            ON rec.path NOT LIKE '%|' + CAST(t1.col2 as varchar(10)) + '%'
               AND rec.path NOT LIKE '%' + CAST(t1.col2 as varchar(10)) + '|%'
        WHERE depth + 1 <= 3 
    
    )
    SELECT * 
    FROM recCTE 
    WHERE depth = 2
    

提交回复
热议问题