我有桌子:T1,T2:
T1:
ID,VAL
T2: ID,ID2,VAL
T1:ID和T2:ID使用相同的值。我需要以这种方式连接上面的表: T3:ID,ID2,T2VAL,T1VAL 其中T3类是完全连接,但它应该具有T2中所有ID的所有ID,即使T2中没有这样的ID,ID2键。
示例:
T1:
0, t1_val_0
1, t1_val_1
2, t1_val_2
3, t1_val_3
T2:
0, id2_0, t2_0_0
1, id2_0, t2_1_0
2, id2_0, t2_2_0
0, id2_1, t2_0_1
T3 as result of the query:
ID, ID2, T2VAL, T1VAL
0, id2_0, t2_0_0, t1_val_0
1, id2_0, t2_1_0, t1_val_1
2, id2_0, t2_2_0, t1_val_2
3, id2_0, null, t1_val_3
0, id2_1, t2_0_1, t1_val_0
1, id2_1, null, t1_val_1
2, id2_1, null, t1_val_2
3, id2_1, null, t1_val_3
所以我需要一个可以连接上面两个表的查询,并返回如上所述的结果。
答案 0 :(得分:1)
所以,这真的很奇怪....但如果这是你想要的,这就是我做的事情(使用Common Table Expressions和Sub-Selects)。鉴于此架构:
CREATE TABLE T1 (ID int, t1 varchar(10))
CREATE TABLE T2 (ID int, id2 varchar(10), t2 varchar(10))
然后将这些数据放入其中:
INSERT INTO T1 (ID, t1)
VALUES (0, 't1_val_0'),
(1, 't1_val_1'),
(2, 't1_val_2'),
(3, 't1_val_3')
INSERT INTO T2 (ID, id2, t2)
VALUES
(0, 'id2_0', 't2_0_0'),
(1, 'id2_0', 't2_1_0'),
(2, 'id2_0', 't2_2_0'),
(0, 'id2_1', 't2_0_1')
我使用此SELECT以您想要的格式提取数据:
;WITH
ID1S AS (
SELECT DISTINCT ID FROM T1
UNION
SELECT DISTINCT ID FROM T2
),
ID2S AS (
SELECT DISTINCT ID2 FROM T2
),
AllIDs AS (
SELECT ID, ID2 FROM ID1S CROSS JOIN ID2S
)
SELECT a.ID, a.ID2,
(SELECT t2 FROM T2 WHERE ID = a.ID AND id2 = a.ID2) AS T2Val,
(SELECT t1 FROM T1 WHERE ID = a.ID)
FROM AllIDs a
ORDER BY a.ID2, a.ID
为了引导您完成它,第一个CTE获得所有ID的完整集合,而第二个CTE获得所有“id2”的完整集合,第三个CTE生成CROSS JOIN以获得这些ID的所有可能组合。这给你前两列。然后将后两个子选择回原始表以填充匹配值,为任何缺失的数据留下NULL。
答案 1 :(得分:0)
不确定这对于更大的数据集是否正确,但是这将带来T1.id和T2.id2的所有组合,然后显示来自T2的数据(如果存在):
;with T (id2) as (
select distinct id2 from T2)
select
T1.id,
T.id2,
T2.tval2,
T1.tval1
from
T1
cross join T
left outer join T2 on
T2.id = T1.id and T2.id2 = T.id2