I have the following two table E
and G
.
create table E(K1 int, K2 int primary key (K1, K2))
insert E
values (1, 11), (1, 20), (2, 10), (2, 30), (3, 10), (3, 30),
(4, 100), (5, 200), (6, 200),
(7, 300), (8, 300), (9, 310), (10, 310), (10, 320), (11, 320), (12, 330)
create table G(GroupID varchar(10), K1 int primary key)
insert G
values ('Group 1', 1), ('Group 1', 2), ('Group 2', 4), ('Group 2', 5),
('Group 3', 8), ('Group 3', 9), ('Group 3', 12)
I need to a view - giving a K2
number, find all related K1
. The "related K1" is defined:
All
K1
s have the sameK2
in tableE
. For example, 2 and 3 inE
are related because both records haveK2
of 10. ((2, 10), (3, 10)).All
K1
s have the sameGroupID
in tableG
. For example, theK1
of 1 and 2 are both in groupGroup 1
.
So querying the following view
select K1 from GroupByK2 where K2 = 200 -- or 100
should return
4
5
6
because both (5, 200)
and (6, 200)
have the same K2
. And the 4 and 5 of (4, 100)
and (5, 200)
are both in 'Group 2'
.
And select K1 from GroupByK2 where K2 = 300 -- or 310, 320, 330
should return 7, 8, 9, 10, 11, 12
.
View:
create view GroupByK2
as
with cte as (
select E.*, K2 K2x from E
union all
select E.K1, E.K2, cte.K2x
from cte
join G on cte.K1 = G.K1
join G h on h.GroupID = G.GroupID
join E on E.K1 = h.K1 and E.K1 <> cte.K1
where not exists (select * from cte x where x.k1 = G.k1 and x.K2 = G.K2) -- error
)
select *
from cte;
However, the SQL has the error of
Recursive member of a common table expression 'cte' has multiple recursive references?