[英]Minus query / operator in Oracle
I am working on a Oracle 11g db. 我正在研究Oracle 11g数据库。 I have Currency Table for which i have 182 records in the year 2013 and for the year 2014, i have 81 records.
我有货币表,在2013年有182条记录,在2014年有81条记录。 I have to get the difference 101 records from 2013. Missing / Difference records i have to insert into the year 2014.
我必须从2013年获得101条记录的差异。我必须在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
);
Your usage of MINUS is correct. 您对MINUS的使用是正确的。 When you want SET difference, MINUS is correct way to go.
当您需要SET差异时,MINUS是正确的选择。 Note that some other databases use EXCEPT keyword for this operation.
请注意,其他一些数据库对此操作使用EXCEPT关键字。
Following set operations are available. 可以进行以下设定操作。
You only need to have the CCYCD
column in the SELECT
list in the MINUS
query. 您只需要在
MINUS
查询的SELECT
列表中具有CCYCD
列。 Now, to insert this result into the table for year 2014, just write an i sert statement like this, 现在,要将此结果插入到2014年的表格中,只需编写这样的i sert语句,
INSERT INTO ccyexc
SELECT ccycd, 2014 as "yearnr"
FROM(
<your MINUS query>
);
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 您也可以使用LEFT JOIN
MINUS doesn't work because both sets (subqueries) have different YEARNR (they don't intersect) MINUS不起作用,因为两个集合(子查询)具有不同的YEARNR(它们不相交)
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. 或者,正如其他人所建议的,
NOT EXISTS
或NOT IN
子句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.