[英]Case when SQL Server 2008
我只有一张没有关系的桌子。 当CountyName是零长度的字符串字段时,我需要Statewide
才能包含在结果集中。 否则,我需要字段的值保持原样,例如: 请注意,在第二列中如何显示“ Statewide”和“ countyName”。 countyName应该是实际存储在数据库中的原始值。
`countyName` `address`
blah blah
Jackson blah blah
需要是(两个示例的第一行都是列名)
countyName address
Statewide blah blah
Jackson blah blah
这是我尝试过的方法,在此示例中,您可以忽略其余字段
select case servicetype
when 'cr' then 'Community Resource'
when 'ed' then 'Education'
when 'fb' then 'Faith-based'
when 'me' then 'Medical Equipment'
when 'hc' then 'Health Care'
else 'Other'
end as serviceType
,case countyName
when '' then 'Statewide'
else 'countyname' end
,name
,physicaladdress
,city
,statelocation
,zip
,phone
,website
from main
order by countyName, servicetype, name
尽管没有确切说明期望的结果,但我的猜测是您不想返回“ countyname”的原义。 您想要的是该列中的值。
因此,尝试将当前的case语句替换为...
,case countyName
when '' then 'Statewide'
else countyName end
作为额外的安全网,您还可以使用ISNULL
...检查NULL
值。
,case ISNULL(countyName,'')
when '' then 'Statewide'
else countyName end
尝试这个:
case when isnull(countyName,'') = '' then 'Statewide' else countyname end
我猜您正在寻找“ IFNULL”功能。
只需以这种方式使用它: SELECT ...,ISNULL( column, "fallback value" ),...
在您的情况下
试试这个... IsNULL应该被检查。
case ISNULL(countyName,'') when '' then 'Statewide' else 'countyname' end
SELECT ProductNumber, Category =
CASE ProductLine
WHEN 'R' THEN 'Road'
WHEN 'M' THEN 'Mountain'
WHEN 'T' THEN 'Touring'
WHEN 'S' THEN 'Other sale items'
ELSE 'Not for sale'
END,
Name
FROM Production.Product
ORDER BY ProductNumber;
走
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.