下面是我尝试加入的2个表,
表1:
+--------+--------+---------+------+-----+--------+
| seq_id | req_id | ctrl_id | CODE | c2 | status |
+--------+--------+---------+------+-----+--------+
| 1 | 3 | C001 | ABC | 0 | PASS |
| 2 | 3 | C001 | EFG | 0 | PASS |
| 3 | 3 | C001 | HIJ | 0 | PASS |
+--------+--------+---------+------+-----+--------+
表2:
+--------+--------+---------+--------+-------+-------------+
| seq_id | Req_id | ctrl_id | source | c1 | c2 |
+--------+--------+---------+--------+-------+-------------+
| 1 | 5 | C001 | S1 | ABC | 32331235662 |
| 2 | 5 | C001 | S1 | EFG | 8966492700 |
| 3 | 5 | C001 | S1 | HIJ | 12656678121 |
| 4 | 5 | C001 | S2 | ABC | 32331235662 |
| 5 | 5 | C001 | S2 | EFG | 8966492700 |
| 6 | 5 | C001 | S2 | HIJ | 12656678121 |
+--------+--------+---------+--------+-------+-------------+
我正在使用以下查询联接这些表,
select a.seq_id, a.req_id, a.ctrl_id, a.CODE,
(case when b.source = 'S1' then b.c2 end) as source1 ,
(case when b.source = 'S2' then b.c2 end) as source2, a.c2, a.status
from table1 a
join table2 b on a.ctrl_id=b.ctrl_id and a.code=b.c1
order by a.seq_id
我得到的结果是
seq_id Req_id ctrl_id CODE SOURCE1 SOURCE2 c2 status
1 5 C001 ABC NULL 32331235662 0 PASS
1 5 C001 ABC 32331235662 NULL 0 PASS
2 5 C001 EFG NULL 8966492700 0 PASS
2 5 C001 EFG 8966492700 NULL 0 PASS
3 5 C001 HIJ NULL 12656678121 0 PASS
3 5 C001 HIJ 12656678121 NULL 0 PASS
我正在尝试获取以下结果,而没有空值
seq_id Req_id ctrl_id CODE SOURCE1 SOURCE2 c2 status
1 5 C001 ABC 32331235662 32331235662 0 PASS
2 5 C001 EFG 8966492700 8966492700 0 PASS
3 5 C001 HIJ 12656678121 12656678121 0 PASS
请协助。
答案 0 :(得分:3)
只需将分组用于此任务
赞
select a.seq_id, a.req_id, a.ctrl_id, a.CODE,
max(case when b.source = 'S1' then b.c2 end) as source1 ,
max(case when b.source = 'S2' then b.c2 end) as source2, a.c2, a.status
from table1 a
join table2 b on a.ctrl_id=b.ctrl_id and a.code=b.c1
group by a.seq_id, a.req_id, a.ctrl_id, a.CODE,a.c2, a.status
order by a.seq_id
答案 1 :(得分:0)
您可以使用联接来获取要使用的两个单独的字段,然后将它们修改为原始数据集。
在这种情况下,联接是到同一表的SELF JOINS,以获得指定的值。
select a.seq_id, b.req_id, a.ctrl_id, a.CODE,
s1.c2 AS [Source1] ,
s2.c2 AS [Source2],
a.c2,
a.status
from table1 a
LEFT OUTER JOIN table2 b
ON a.seq_id = b.seq_id
LEFT OUTER JOIN table2 s1
ON s1.req_id = b.req_id AND s1.c1 = b.c1 AND s1.[source] = 'S1'
LEFT OUTER JOIN table2 s2
ON s2.req_id = b.req_id AND s2.c1 = b.c1 AND s2.[source] = 'S2'
order by a.seq_id