如果列具有Y值,则在列中添加值x的SQL查询

时间:2014-08-25 13:31:34

标签: sql sql-server sql-server-2008-r2

Machine ID     Hostname     IP Address
1              Test 1       10.216.x.x
2              Test 2       10.218.x.x
3              Test 3       172.21.x.x
5              Test 4       192.25.x.x

我需要添加一个列,其中10.216.x.x段将是Chennai而192.25.X.X将是德里等

Machine ID     Hostname     IP Address    Location
1              Test 1       10.216.x.x    Chennai
2              Test 2       10.218.x.x    Mumbai
3              Test 3       172.21.x.x    NOIDA
5              Test 4       192.25.x.x    Delhi

SQL Server 2008 R2 ..

我们怎样才能在查询中得到这个?

2 个答案:

答案 0 :(得分:0)

以下内容(SQL Fiddle):

SELECT [Machine ID], Hostname, [IP Address], 
CASE WHEN [IP Address] LIKE '10.216%' THEN 'Chennai'
     WHEN [IP Address] LIKE '10.218%' THEN 'Mumbai'
     WHEN [IP Address] LIKE '172.21%' THEN 'NOIDA'
     WHEN [IP Address] LIKE '192.25%' THEN 'Delhi'
     ELSE 'UNKNOWN' END
FROM MyTable

答案 1 :(得分:0)

SELECT [Machine ID]     
      ,Hostname     
      ,[IP Address]
      ,CASE 
           WHEN LEFT([IP Address] , 6) = '10.216' THEN 'Chennai'
           WHEN LEFT([IP Address] , 6) = '10.218' THEN 'Mumbai'
           WHEN LEFT([IP Address] , 6) = '192.25' THEN 'Delhi'
           WHEN LEFT([IP Address] , 6) = '172.21' THEN 'NOIDA'
       END AS [Location]
FROM Table_Name