如何使用 SQL (Oracle DB) 从一组值中找到缺失值,例如
SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)
(“IN”子句可能包含数百个值)如果 ACCOUNT 表中缺少“现代”,我需要将结果作为“现代”。
目前我使用上述查询的结果对原始值集进行 Vlookup 以查找缺失值,我想直接获取缺失值而不进行 Vlookup。
谢谢基兰,
你把它弄反了。这样做:http ://www.sqlfiddle.com/#!2/09239/3
SELECT Brand
FROM
(
-- Oracle can't make a row without a table, need to use DUAL dummy table
select 'FORD' as Brand from dual union
select 'HYUNDAI' from dual union
select 'TOYOTA' fom dual union
select 'BMW' from dual
) x
where Brand not in (select BrandName from account)
示例帐户数据:
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
输出:
| BRAND |
-----------
| HYUNDAI |
更好的是,将品牌具体化到一张桌子上:
select *
from Brand
where BrandName not in (select BrandName from account)
输出:
| BRANDNAME |
-------------
| HYUNDAI |
样本数据和现场测试:http ://www.sqlfiddle.com/#!2/09239/1
CREATE TABLE Brand
(`BrandName` varchar(7));
INSERT INTO Brand
(`BrandName`)
VALUES
('FORD'),
('HYUNDAI'),
('TOYOTA'),
('BMW');
create table account(AccountId int, BrandName varchar(10));
insert into account(AccountId, BrandName) values
(1,'FORD'),
(2,'TOYOTA'),
(3,'BMW');
您应该使用except: EXCEPT 返回左侧查询中未在右侧查询中找到的任何不同值。
WITH SomeRows(datacol) --It will look for missing stuff here
AS( SELECT *
FROM ( VALUES ('FORD'),
('TOYOTA'),
('BMW')
) AS F (datacol)),
AllRows (datacol) --This has everthing
AS( SELECT *
FROM ( VALUES ('FORD'),
('HYUNDAI'),
('TOYOTA'),
('BMW')
) AS F (datacol))
SELECT datacol
FROM AllRows
EXCEPT
SELECT datacol
FROM SomeRows
你可以做:
SELECT a.val
FROM
(
SELECT 'FORD' val UNION ALL
SELECT 'HYUNDAI' UNION ALL
SELECT 'TOYOTA' UNION ALL
SELECT 'BMW' UNION ALL
etc...
etc...
) a
LEFT JOIN account b ON a.val = b.name
WHERE b.name IS NULL
这工作得很好,谢谢迈克尔。
SELECT Brand
FROM
( -- Oracle can't make a row without a table, need to use DUAL dummy table
select 'FORD' as Brand from dual union
select 'HYUNDAI' from dual union
select 'TOYOTA' fom dual union
select 'BMW' from dual
)
where Brand not in (select BrandName from account)
Luxspes 和 Zane 感谢您的投入
贡献 Excel 代码以使输入答案更容易:
假设 A 列具有值(福特、现代、...)。
在 B 列中,将其放在每个单元格中:
select 'x' as brand from dual union
在 C 列中,写下这个公式,并将其复制下来。
=REPLACE(A2,9,1,A1)
所有 select
/union
语句都应出现在 C 列中。