我有2个表A和B,其中包含以下数据:(我使用的是oracle 11g)
我需要根据字段“Code”将上面的2个表合并到1个表中。这个插图只是我工作中更大问题的简化版本。基本上,我有一个结构存储在B中的表单和存储在A中的响应。但是,保存响应的表A不保留存储在B中的标题。在报告中,我需要打印标题以及响应。无论如何,不想让问题复杂化,我正在寻找的结果是以下格式:
使用select,join和可能的联合生成我想要的结果是否可行?我不能让它发挥作用。到目前为止,我能提出的陈述是:
select * from b left outer join a
on b."Code"= a."Code"
但结果并不是我想要的。如果没有创建格式化程序,这是否可行。理想情况下,它应该放在视图中
以下是生成测试数据的脚本:
CREATE TABLE "A"
( "Id" NUMBER,
"Row" NUMBER,
"Description" VARCHAR2(20 BYTE),
"Type" NUMBER,
"Answer" VARCHAR2(20 BYTE),
"Code" VARCHAR2(20 BYTE),
"ClientId" NUMBER
) ;
Insert into A ("Id","Row","Description","Type","Answer","Code","ClientId") values (1,1,'Question 1',2,'ABC','QCONTROL',1000);
Insert into A ("Id","Row","Description","Type","Answer","Code","ClientId") values (2,3,'Question 2',2,'DEC','QCONTROL',1000);
Insert into A ("Id","Row","Description","Type","Answer","Code","ClientId") values (1,1,'Question 1',2,'XYZ','QCONTROL',2000);
Insert into A ("Id","Row","Description","Type","Answer","Code","ClientId") values (2,3,'Question 2',2,'STU','QCONTROL',2000);
Insert into A ("Id","Row","Description","Type","Answer","Code","ClientId") values (3,1,'Question 5',3,'JKL','QCONTROL',3000);
CREATE TABLE "B"
( "Id" NUMBER,
"Desc" VARCHAR2(20 BYTE),
"Row" NUMBER,
"Type" NUMBER,
"Code" VARCHAR2(20 BYTE)
) ;
Insert into B ("Id","Desc","Row","Type","Code") values (10,'----------',2,0,'QCONTROL');
Insert into B ("Id","Desc","Row","Type","Code") values (20,'**********',10,0,'OTHER');
答案 0 :(得分:1)
这就是你想要的吗?
with res as(
select "Id" , "Row" , "Description" , "Type" , "Answer", "Code", "ClientId" from A
union all
select B."Id" as "Id" , B."Row" as "Row" , B."Desc" as "Description",
B."Type" as "Type", null as "Answer", B."Code" as "Code", A1."ClientId" as "ClientId"
from B inner join (select distinct "ClientId", "Code" from A) A1 ON B."Code"= A1."Code"
)
select * from res order by "Code", "ClientId", "Answer"
答案 1 :(得分:0)
我不确定语法(我不在oracle实例前面......),但我的脚本可以作为一个起点。
Select * from
(Select Id, '9999' as Row, Desc,0 as type, B.Code, A.ClientId
from B, A
where A.Code=B.Code
union all
Select * from A) ab
order by ab.ClientId, ab.row
我把一个' 9999'在Row中以正确的方式排序。 我希望它能有所帮助!
答案 2 :(得分:0)
抱歉,我无法理解您的确切要求,但下面提到的查询将返回结果,如屏幕截图所示。我已经重命名了像Row to Row1这样的列,因为我不喜欢在查询中使用双引号。
WITH subqueryfactoring AS
(SELECT A.id,
A.row1,
A.description,
A.type1,
A.answer,
A.code,
A.clientid
FROM A
INNER JOIN B
ON A.code=B.code
UNION
SELECT B.id,
B.row1,
B.desc1,
B.type1,
NULL,
B.code,
A.clientid
FROM A
INNER JOIN B
ON A.code=b.code
)
SELECT * FROM subqueryfactoring ORDER BY clientid, id nulls last;