Sql server 2005 SQL Server别名中两个varchar列的总和
我有一张如下所示的表格Sql server 2005 SQL Server别名中两个varchar列的总和,sql-server-2005,concatenation,alias,calculated-columns,Sql Server 2005,Concatenation,Alias,Calculated Columns,我有一张如下所示的表格 declare @Location Table([state] nvarchar(30) null,city nvarchar(30) null) Insert Into @Location Values('California', 'San Francisco') Insert Into @Location Values('California', null) Insert Into @Location Values('California', 'Orange Cou
declare @Location Table([state] nvarchar(30) null,city nvarchar(30) null)
Insert Into @Location Values('California', 'San Francisco')
Insert Into @Location Values('California', null)
Insert Into @Location Values('California', 'Orange County')
Insert Into @Location Values('California', null)
select
[state], city, [state] as CurrentState,
case
when city is null then 'Sacramento'
else city
end as CurrentCity
from
@Location
和select语句,如下所示
declare @Location Table([state] nvarchar(30) null,city nvarchar(30) null)
Insert Into @Location Values('California', 'San Francisco')
Insert Into @Location Values('California', null)
Insert Into @Location Values('California', 'Orange County')
Insert Into @Location Values('California', null)
select
[state], city, [state] as CurrentState,
case
when city is null then 'Sacramento'
else city
end as CurrentCity
from
@Location
我想要第五列,标题为Address
,它给出了CurrentState
和CurrentCity
列的总和,如下所示:
Address
California, San Francisco
California, Sacramento
California, Orange County
California, Sacramento
这可能吗
我已经试过了
CurrentState+,'+CurrentCity
。它不起作用这将满足您的要求:
select [state], city, [state] as CurrentState,
coalesce(city, 'Sacramento') as CurrentCity,
(coalesce(city, 'Sacramento') + ', ' + coalesce(state, '')) as Address,
from @Location;
也就是说,你需要重复这个逻辑。但是coalesce()
比case
语句要简单得多。这同样有效
select
[state], city, [state] as CurrentState,
case
when city is null then 'Sacramento'
else city
end as CurrentCity,
case
when city is null then [state] + ', ' + 'Sacramento'
else [state] + ', ' + [city]
end as Address
from
@Location
要不是更干净的方法,我宁愿
SELECT
[STATE]
,[CITY]
,CurrentState = [STATE]
,CurrentCity = ISNULL ([CITY] , 'Sacramento')
,Address = [STATE] + ', ' + ISNULL ([CITY] , 'Sacramento')
FROM @Location
或
我知道您已经标记了SQLServer2005,但是,如果您在未来的SQLServer2012中使用,您甚至可以尝试使用IIF语句作为
SELECT
[STATE]
,[CITY]
,CurrentState = [STATE]
,CurrentCity = IIF([CITY] IS NULL,'Sacramento',[CITY])
,Address= IIF([CITY] IS NULL,
[STATE] + ', ' +'Sacramento',
[STATE] + ', ' +[CITY])
FROM @Location
或使用选择,如下所示
SELECT
[STATE]
,[CITY]
,CurrentState = [STATE]
,CurrentCity = CHOOSE(IIF([CITY] IS NULL,1,2),'Sacramento',[CITY])
,Address= CHOOSE(IIF([CITY] IS NULL,1,2),[STATE] + ', ' +'Sacramento',[STATE] + ', ' +[CITY])
FROM @Location
所有这些都会产生相同的结果
希望这会有帮助。只需执行
city+,“+state
@Gordon:city,state会给我实际的列值和空值。这一定是化名,谢谢戈登。这很有帮助。