[英]How to write this SQL for linking data in DB2?
For example, there are two columns - ID1 and ID2 which are linked to each other. 例如,有两列--ID1和ID2相互链接。 It is possible that the IDs are linked with other IDs in the table.
ID可能与表中的其他ID链接。
ID1 ID2
------------------
001 002
001 003
004 005
002 006
005 007
In the above table, 001, 002, 003, 006 are linked and 004, 005, 007 are linked. 在上表中,001,002,003,006被链接并且004,005,007被链接。
Is it possible to query this information in SQL for DB2? 是否可以在SQL for DB2中查询此信息?
The format is similar as the following: 格式类似如下:
Group ID
--------------
1 001
1 002
1 003
1 006
2 004
2 005
2 007
On the other hand, if one more record (008, 007) is added to the table 另一方面,如果向表中添加一个记录(008,007)
ID1 ID2
------------------
001 002
001 003
004 005
002 006
005 007
008 007 (Newly added)
The expected result will be: 预期结果将是:
Group ID
--------------
1 001
1 002
1 003
1 006
2 004
2 005
2 007
2 008
because 004, 005, 007, 008 are linked. 因为004,005,007,008是相互关联的。
The DB2 Version is 9.7. DB2版本是9.7。
Sure you can! 你当然可以! It requires a recursive query:
它需要递归查询:
WITH Recur (grp, root, leaf) as (SELECT ROW_NUMBER() OVER(ORDER BY root.id1),
CAST(NULL as CHAR(3)),
root.id1
FROM Linked as root
EXCEPTION JOIN Linked as leaf
ON leaf.id2 = root.id1
GROUP BY root.id1
UNION ALL
SELECT grp, leaf, id2
FROM Recur
JOIN Linked
ON id1 = leaf)
SELECT grp, leaf
FROM Recur
ORDER BY grp, leaf
(Tested on my local iSeries, and have a working SQL Fiddle example , which has to use the LEFT JOIN
-style exception to work in SQL Server) (在我的本地iSeries上测试过,并且有一个有效的SQL Fiddle示例 ,它必须使用
LEFT JOIN
style异常才能在SQL Server中工作)
Yields the expected output: 产生预期的输出:
grp leaf
=============
1 001
1 002
1 003
1 006
2 004
2 005
2 007
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.