使用SQL从一组值中查找缺少的值

时间:2012-07-13 05:18:54

标签: sql oracle in-clause

如何使用SQL(Oracle DB)从一组值中找到缺失值 e.g。

SELECT NAME
FROM ACCOUNT
WHERE ACCOUNT.NAME IN ('FORD','HYUNDAI','TOYOTA','BMW'...)

(" IN"子句可能包含数百个值) 如果' HYUNDAI'在ACCOUNT表中缺少,我需要得到结果为" HYUNDAI"。

目前我使用上述查询的结果对原始值集进行Vlookup查找缺失值,我想直接获取缺失值而不进行Vlookup。

由于 吉兰,

5 个答案:

答案 0 :(得分:6)

你把它颠倒了。这样做: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');

答案 1 :(得分:0)

您应该使用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

答案 2 :(得分:0)

你可以这样做:

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

答案 3 :(得分:0)

这非常有效,谢谢Michael。

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感谢您的投入

答案 4 :(得分:-1)

提供Excel代码以便更轻松地输入答案:

说A栏有值(福特,现代,......)。

在B栏中,将其放在每个单元格中:

select 'x' as brand from dual union

在C列中,编写此公式并将其复制下来。

=REPLACE(A2,9,1,A1)

所有select / union语句都应出现在C列中。