简体   繁体   中英

Insert using different conditions with same date - Oracle 10g

--Table Creation
CREATE TABLE BOOK_TEST (BOOK_ID VARCHAR2(20), DEP_IND VARCHAR2(1), INSERT_DATE DATE);
--Insert data
INSERT INTO BOOK_TEST VALUES ('B100','Y','20122016');
INSERT INTO BOOK_TEST VALUES ('B101','Y','20122016');
INSERT INTO BOOK_TEST VALUES ('B101','N','20122016');
INSERT INTO BOOK_TEST VALUES ('B102','Y','20122016');
INSERT INTO BOOK_TEST VALUES ('B103','Y','20122016');
INSERT INTO BOOK_TEST VALUES ('B104','N','20122016');
INSERT INTO BOOK_TEST VALUES ('B105','N','20122016');
INSERT INTO BOOK_TEST VALUES ('B105','Y','20122016');
INSERT INTO BOOK_TEST VALUES ('B106','N','30092016');
INSERT INTO BOOK_TEST VALUES ('B107','Y','03032016');
COMMIT;

Question: I want to insert above all records into target table(target_book) as one booking id has one indicator (B101-'Y') then it's populate into target table and same time suppose (B101-'N') booking id has an different indicator is 'N' then this records should not comes to target table (target_book).All the above two conditions should comes under the same date and this is the very big challenging I'm facing.

SAMPLE QUERY:-

CREATE TABLE TARGET_BOOK AS SELECT * FROM BOOK_TEST WHERE (--conditions?)

Finally my target_book table should be populated with below result.

B_ID DEP_IND DATE
B100 Y 20122016
B101 Y 20122016
B102 N 20122016
B103 Y 20122016
B104 Y 20122016
B105 Y 20122016
B106 N 30092016
B107 Y 03032016

Try this:

CREATE TABLE TARGET_BOOK AS 
SELECT BOOK_ID, DEP_IND, INSERT_DATE
FROM (
   SELECT BOOK_ID, DEP_IND, INSERT_DATE,
          ROW_NUMBER() OVER (PARTITION BY BOOK_ID 
                             ORDER BY CASE 
                                         WHEN DEP_IND = 'Y' THEN 0 
                                         ELSE 1
                                      END)  rn
   FROM BOOK_TEST)  t
WHERE t.rn = 1    

Using ROW_NUMBER you can enumerate records within each BOOK_ID partition and give precedence to records having DEP_IND = 'Y' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM