我有一个SQL表,它由两列没有列id组成,两列是汽车等效部分的组合,需要在一列中返回所有可能的关系,给出一列或另一列的元素,例如,给定值是530:
ColunaA ColunaB
530 520
530 510
530 444
444 222
333 111
最终结果必须是:
Column X
530
520
510
444
222
我尝试了这个SQL查询:
WITH AreasCTE AS
(
SELECT colunaa, colunab FROM dbo.Tabela1 WHERE colunaa = '530'
UNION ALL
SELECT a.colunaa, a.colunab FROM dbo.Tabela1 a
INNER JOIN AreasCTE s ON a.colunaa = s.colunaa
)
SELECT top 100 colunaa, colunab FROM AreasCTE
感谢您的帮助!!
答案 0 :(得分:0)
试试这个,它不是完美的解决方案可能需要一些性能调整,但应该完成这项工作。
DECLARE @t1 TABLE
(
colunaA NVARCHAR(MAX) ,
colunaB NVARCHAR(MAX)
);
INSERT INTO @t1
VALUES ( 530, 520 ) ,
( 530, 510 ) ,
( 530, 444 ) ,
( 444, 222 ) ,
( 333, 111 );
SELECT *
FROM @t1;
DECLARE @value NVARCHAR(MAX);
SET @value = 222;
DECLARE @filter TABLE
(
id NVARCHAR(MAX)
);
INSERT INTO @filter
VALUES ( @value );
DECLARE @right_row_count INT;
DECLARE @left_row_count INT;
SET @left_row_count = 1;
WHILE @left_row_count > 0
OR @right_row_count > 0
BEGIN
INSERT INTO @filter ( id )
SELECT DISTINCT t.colunaA
FROM @t1 t
INNER JOIN @filter f ON t.colunaB = f.id
WHERE t.colunaA NOT IN ( SELECT *
FROM @filter );
SET @right_row_count = @@rowcount;
INSERT INTO @filter ( id )
SELECT DISTINCT t.colunaB
FROM @t1 t
INNER JOIN @filter f ON t.colunaA = f.id
WHERE t.colunaB NOT IN ( SELECT *
FROM @filter );
SET @left_row_count = @@rowcount;
END;
SELECT *
FROM @filter
ORDER BY id DESC;