选择加入时的唯一字段

时间:2019-01-17 02:55:50

标签: sql oracle join unique

CREATE TABLE Face.Person 
   ("LAST_NAME" VARCHAR2(50 BYTE), 
    "TICKET_NUMBER" VARCHAR2(50 BYTE));

insert into Person(last_name,ticket_number) values('johnson','100');
insert into Person(last_name,ticket_number) values('smith','200');

CREATE TABLE Face.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));

insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ ) values('100', 'S', 'F1', '111', 'Mia', 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', 'PBI', 3);
insert into Orders(ticket_number, REGION, STATE, STORE_NUM, A_CODE, SEQ ) values('100', 'S', 'F1', '444', 'BOC', 4);


SELECT A.LAST_NAME, A.TICKET_NUMBER, B.REGION, B.STATE 
FROM PERSON A
  JOIN Orders B ON A.TICKET_NUMBER 
    = (SELECT * FROM Orders WHERE A.TICKET_NUMBER= B.TICKET_NUMBER 
  AND ROWNUM = 1);

同时加入票号的两个表格。人与订单是一对多的关系。存在多个订单,但只需要一个与两个表中的凭单号匹配的Orders记录(共4个)。原因是对于所有具有相同凭单号的记录,Orders表中的必填字段保持不变。

预期结果:

Johnson 100 S Fl 

Johnson和person表中的100和S和FL,对于每个唯一凭单号的所有记录都相同,来自Orders

Oracle 12c

1 个答案:

答案 0 :(得分:1)

目前尚不清楚您从Orders中选择记录的依据。一种选择是简单地选择MIN()region中的state和group by,然后将其与Person

加入
WITH b AS (
     SELECT ticket_number,
            MIN(region) AS region,
            MIN(state) AS state
     FROM orders
     GROUP BY ticket_number
) SELECT a.last_name,
         a.ticket_number,
         b.region,
         b.state
  FROM person a
  JOIN b ON a.ticket_number = b.ticket_number;

Demo