表列拆分为sql中的两列?

时间:2012-11-22 07:19:31

标签: sql sql-server pivot

在sql server中,我在表中有一列,我想在另一个表[new table]中将列放在两列中。你能帮帮我吗?

------------------------
  Type
  ------------------------
  UserDefine

  UserDefine

  AutoGenerate

  AutoGenerate

  UserDefine
 -------------------------

以上是我在我的一个表格中的列现在我想在两个列中创建像UserDefine和Autogenerate列在不同的表中

  -----------------------------------
   UserDefine        | AutoGener      |
  ------------------------------------|
  UserDefine         |   AutoGenerate | 
                     |                |
  UserDefine         |   AutoGenerate |
 ---------------------------------------

如上所述,请帮助我谢谢。

2 个答案:

答案 0 :(得分:0)

我会使用两个插入,一个用于“UserDefine”值,另一个用于“AutoGenerate”

INSERT INTO NewTable (UserDefine) SELECT Type FROM OldTable WHERE Type = "UserDefine"

INSERT INTO NewTable (UserDefine) SELECT Type FROM OldTable WHERE Type = "AutoGenerate"

将where子句更改为apropiate条件以区分这两种类型。

答案 1 :(得分:0)

试试这个:

;WITH CTE
AS
(
  SELECT *, ROW_NUMBER() OVER(PARTITION BY [Type] ORDER BY [Type]) rownum
  FROM Table1
)
SELECT 
  MAX(CASE WHEN [Type] = 'AutoGenerate' THEN [Type] END) AS 'AutoGenerate',
  MAX(CASE WHEN [Type] = 'UserDefine' THEN [Type] END) AS 'UserDefine'
FROM CTE
WHERE Rownum <= 2
GROUP BY Rownum;

SQL Fiddle Demo