I am working on a Oracle 11g db. I have Currency Table for which i have 182 records in the year 2013 and for the year 2014, i have 81 records. I have to get the difference 101 records from 2013. Missing / Difference records i have to insert into the year 2014.
I wonder whether my syntax is incorrect or any other method to generate the difference query.
SELECT
a.CCYCD,
a.YEARNR
FROM CCYEXC a
WHERE a.YEARNR = 2013
minus
SELECT
a.CCYCD,
a.YEARNR
FROM CCYEXC a
WHERE a.YEARNR = 2014;
SELECT CCYCD
, YEARNR
FROM CCYEXC
WHERE YEAR_NR = 2014
AND CCYCD,YEARNR NOT IN
(
SELECT CCYCD
, YEARNR
FROM CCYEXC
WHERE YEAR_NR = 2013
);
You only need to have the CCYCD
column in the SELECT
list in the MINUS
query. Now, to insert this result into the table for year 2014, just write an i sert statement like this,
INSERT INTO ccyexc
SELECT ccycd, 2014 as "yearnr"
FROM(
<your MINUS query>
);
EXISTS usually faster:
SELECT a.CCYCD, a.YEARNR
FROM CCYEXC a
WHERE a.YEARNR = 2013
and not exists (select 1 from CCYEXC b where b.YEARNR = 2014 and b.CCYCD = a.CCYCD);
Another option:
SELECT a.CCYCD, a.YEARNR
FROM CCYEXC a
WHERE a.YEARNR = 2013
and a.CCYCD not in (select distinct CCYCD from CCYEXC b where b.YEARNR = 2014);
Also you can use LEFT JOIN
MINUS doesn't work because both sets (subqueries) have different YEARNR (they don't intersect)
A shorter way to write this is to use aggregation:
SELECT c.CCYCD,
FROM CCYEXC c
GROUP BY c.CCYCD
HAVING SUM(CASE WHEN c.YEARNR = 2013 THEN 1 ELSE 0 END) > 0 AND
SUM(CASE WHEN c.YEARNR = 2014 THEN 1 ELSE 0 END) = 0;
Or, as others have suggested, a NOT EXISTS
or NOT IN
clause.
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.