联接两个表并返回第二个表的第一条记录-拥有此代码。第二个表中的一列可以具有相同的值。如果是这样,则返回该值;否则返回0。否则,返回null。
使用了distinct,但即使列值不是distinct(即返回null),仍需要返回第一条记录
CREATE TABLE Person ("LAST_NAME" VARCHAR2(50 BYTE),
"TICKET_NUMBER" VARCHAR2(50 BYTE));
BEGIN
insert into Person(last_name,ticket_number) values('johnson','100');
insert into Person(last_name,ticket_number) values('smith','200');
END;
/
CREATE TABLE Orders
("REGION" VARCHAR2(50 BYTE),
"STATE" VARCHAR2(50 BYTE),
"A_CODE" VARCHAR2(5 BYTE),
"STORE_NUM" VARCHAR2(50 BYTE),
"TICKET_NUMBER" VARCHAR2(50 BYTE),
"SEQ" NUMBER(12));
SELECT a.last_name,
a.ticket_number,
b.region,
b.state,
b.SEQ1,
B.A_CODE
FROM person a
BEGIN
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '111', 'FLL', 1);
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '222', 'FLL', 2);
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '333', 'FLL', 3);
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '444', 'FLL', 4);
END;
/
JOIN (SELECT ticket_number, MIN(SEQ) AS SEQ1,
MIN(region) AS region,
MIN(state) AS state, MIN(A_CODE) AS A_CODE
FROM orders WHERE REGION IS NOT NULL
GROUP BY ticket_number) b ON a.ticket_number = b.ticket_number where
a.last_name is not null;
A_CODE值相同-返回值
LAST_NAME TICKET_NUMBER REGION STATE SEQ1 A_CODE
johnson 100 S F1 1 FLL
但是,如果A_CODE的值不是唯一的(即不相同),则对于A_CODE列返回null,并且仍然返回第二个表的第一条记录。 注意:作为一种选择,如果不相等,则列值不需要返回null。它可以返回“不等于”之类的文字
LAST_NAME TICKET_NUMBER REGION STATE SEQ1 A_CODE
johnson 100 S F1 1 (NULL)
Oracle Database 12c企业版12.2.0.1.0版-64位生产
答案 0 :(得分:0)
下面是查询
SELECT a.last_name,
a.ticket_number,
b.region,
b.state,
b.SEQ1,
case when B.MIN_A_CODE = B.MAX_A_CODE then B.MIN_A_CODE else 'NULL' end A_CODE
FROM person a
JOIN ( SELECT ticket_number, MIN(SEQ) AS SEQ1,
MIN(region) AS region,
MIN(state) AS state, MIN(A_CODE) AS MIN_A_CODE, max(A_CODE) as MAX_A_CODE
FROM orders WHERE REGION IS NOT NULL
GROUP BY ticket_number) b ON a.ticket_number = b.ticket_number where
a.last_name is not null;
我在表格订单中又增加了一行。
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '111', 'FLL', 1);
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '222', 'FLL', 2);
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '333', 'FLL', 3);
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '444', 'FLL', 4);
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ )
values('100', 'S', 'F1', '444', 'DLL', 4);
O / p-
LAST_NAME TICKET_NUMBER REGION STATE SEQ1 A_CODE
johnson 100 S F1 1 NULL
我的理解是,对于同一区域,您具有不同的A_CODE,因此您需要为A_CODE输入null,但所有其他列的值都应该是第一条记录。
希望这会有所帮助