简体   繁体   English

何时基于空值产生值

[英]CASE WHEN to produce value based on null values

With the table CARS : 与桌子CARS

Make   | Model   | Color | Year
------- --------- ------- -----
Honda  | Accord  | Red   | 09
Nissan | Skyline | Blue  | 15
null   | Skyline | Red   | 15
Toyota | null    | Black | 15

I'm trying to produce the string ERROR in the Make column when Make contains a value but Model does not. 我试图在Make包含一个值但Model不包含时在Make列中生成字符串ERROR My statement doesn't produce anything currently 我的陈述目前没有任何结果

SELECT 
CASE
WHEN (SELECT Count(*) 
    FROM CARS
    WHERE a.make=make
    AND a.year=year
    AND a.color=color
    AND a.model = NULL) AND (SELECT Count(*) 
    FROM CARS
    WHERE a.year=year
    AND a.color=color
    AND a.make = make) > 1 THEN '**ERROR**'
ELSE a.make
END as make
FROM a.CARS

If you want to have ERROR as the value for make when make doesn't have any value, but model does then this might be what you want: 如果当make没有任何值,但model有值时,您希望将ERROR作为make的值,那么这可能是您想要的:

SELECT 
    CASE 
       WHEN make IS NULL AND model IS NOT NULL 
       THEN 'ERROR' 
       ELSE make 
    END AS make, 
    model, color, year 
FROM cars;

Or maybe I misunderstood your intent. 也许我误解了你的意图。 Your question doesn't seem to say the same as the comment you posted to another answer. 您的问题似乎与您发布到其他答案的评论不同。

create table cars
(
make varchar(100) null,
model varchar(100) null,
color varchar(100) null,
year int null
);
insert cars(make,model,color,year) values ('honda','accord','red',2009);
insert cars(make,model,color,year) values ('nissan','skyline','blue',2015);
insert cars(make,model,color,year) values (null,'skyline','red',2015);
insert cars(make,model,color,year) values ('toyota',null,'black',2015);


select 
(case when c.make is null then 'ERROR' else c.make end) as make,
(case when c.model is null then 'ERROR' else c.model end) as model,
c.color, c.year
from cars c;

Edit : 编辑

select c.make,c.model,c.color,c.year,
case when (   (c.make is null and c.model is not null) or (c.model is null and c.make is not null)    ) then 'ERROR' else '' end as col5
from cars c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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