SQL从另一列的值创建列

时间:2012-07-11 18:47:39

标签: mysql sql-server

我有下表:

|  id  |         name            |
----------------------------------
|  1   | 236 SRTD - Something 1  |
----------------------------------
|  2   | 236 SRTD - Something 2  |
----------------------------------
|  3   | 236 SRTD - Something 3  |
----------------------------------
|  4   | 387 SRTD - Something 1  |

从该表我想构建另一个类似的视图,但看起来如下:

|  id  |  SRTD  |         name            |
-------------------------------------------
|  1   |  236   | 236 SRTD - Something 1  |
-------------------------------------------
|  2   |  236   | 236 SRTD - Something 2  |
-------------------------------------------
|  3   |  236   | 236 SRTD - Something 3  |
-------------------------------------------
|  4   |  387   | 387 SRTD - Something 1  |

如何修改名称列,获取SRTD编号,然后创建包含该值的另一​​列。

1 个答案:

答案 0 :(得分:3)

对于SQL Server:

SELECT id, SRTD = SUBSTRING(name, 1, CHARINDEX(' ', name)), name
  FROM dbo.table;