SQL Server与别名的两个varchar列的总和

时间:2015-10-19 16:13:06

标签: 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 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

enter image description here

我想要一个标题为Address的第五列,它为我提供了CurrentStateCurrentCity列的总和,如下所示:

Address
California, San Francisco
California, Sacramento
California, Orange County
California, Sacramento

这可能吗?

我已经尝试过CurrentState+', '+CurrentCity了。它不起作用

2 个答案:

答案 0 :(得分:1)

这将做你想要的:

select [state], city, [state] as CurrentState, 
       coalesce(city, 'Sacramento') as CurrentCity, 
       (coalesce(city, 'Sacramento') + ', ' + coalesce(state, '')) as Address, 
from @Location;

也就是说,你需要重复逻辑。但是coalesce()case语句简单得多。

答案 1 :(得分:1)

这也有效

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

OR

SELECT
    [STATE]
    ,[CITY]
    ,CurrentState = [STATE]
    ,CurrentCity = COALESCE ([CITY] , 'Sacramento')
    ,Address = [STATE] + ', ' + COALESCE ([CITY] , 'Sacramento')
FROM @Location

我知道您已经使用SQLServer 2005进行了标记,但是,如果您在将来的Sql Server2012中使用,您甚至可以尝试使用 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

所有产生相同的结果

enter image description here

希望这会有所帮助。