我需要加入多个表中多列的值
离
userid username answeredquestion1 answeredquestion2
1 aa 1 1
2 bb 1 0
我需要结果
userid username question name response
1 aa answertoquestion1 1
2 bb answertoquestion2 0
如果值为null
,则不应复制第一个表中的数据
我使用了以下命令,但它不起作用
INSERT ALL
WHEN AnswerToQuestion1 > 0 --and userid not in (Select Userid from b) --and AnswerToQuestion1 not in (Select AnswerToQuestion from b)
THEN
INTO b (userid, username, AnswerToQuestion) VALUES (UserID, UserName, AnswerToQuestion1)
WHEN AnswerToQuestion2 > 0 --and userid not in (Select Userid from b) --and AnswerToQuestion2 not in (Select AnswerToQuestion from b)
THEN
INTO b (userid, username, AnswerToQuestion) VALUES (UserID, UserName, AnswerToQuestion2)
WHEN AnswerToQuestion3 > 0 --and userid not in (Select Userid from b) --and AnswerToQuestion3 not in (Select AnswerToQuestion from b)
THEN
INTO b (userid, username, AnswerToQuestion) VALUES (UserID, UserName, AnswerToQuestion3)
SELECT UserID, UserName, AnswerToQuestion1, AnswerToQuestion2, AnswerToQuestion3
FROM a
where not exists (SELECT userid, ANSWERTOQUESTION FROM b where b.userid=a.userid and
a.ANSWERTOQUESTION2 = b.ANSWERTOQUESTION)
(或)
insert into b
(select userID,username,AnswerToQuestion2 as AnswerToQuestion from a where
union all
select userID,username,AnswerToQuestion1 as AnswerToQuestion from a)
这个将重复数据,这意味着重复值重复
我需要满足的条件是需要检查第一个表中的4列和第二个表中的3列。 任何人都可以建议我解决方案
提前致谢
答案 0 :(得分:0)
在Oracle中,您可以使用MERGE
子查询中的UNPIVOT
语句来使用USING
:
Oracle 11g R2架构设置:
CREATE TABLE A (
userid INTEGER,
username VARCHAR2(20),
answeredquestion1 NUMBER(1,0),
answeredquestion2 NUMBER(1,0)
);
INSERT INTO A
SELECT 1, 'aa', 1, 1 FROM DUAL UNION ALL
SELECT 2, 'bb', 1, 0 FROM DUAL;
CREATE TABLE B (
userid INTEGER,
username VARCHAR2(20),
question_name VARCHAR2(20),
response NUMBER(1,0)
);
MERGE INTO B dst
USING (
SELECT userid, username, question_name, response
FROM A
UNPIVOT (
response
FOR question_name IN (
answeredquestion1 AS 'answertoquestion1',
answeredquestion2 AS 'answertoquestion2'
)
)
) src
ON ( src.userid = dst.userid AND src.question_name = dst.question_name )
WHEN NOT MATCHED THEN
INSERT ( userid, username, question_name, response )
VALUES ( src.userid, src.username, src.question_name, src.response );
查询1 :
SELECT *
FROM B
<强> Results 强>:
| USERID | USERNAME | QUESTION_NAME | RESPONSE |
|--------|----------|-------------------|----------|
| 2 | bb | answertoquestion1 | 1 |
| 2 | bb | answertoquestion2 | 0 |
| 1 | aa | answertoquestion1 | 1 |
| 1 | aa | answertoquestion2 | 1 |