Table column split to two columns in sql?

2019-06-06 20:41发布

In sql server, I have once column in the table, i want to make the column in two column, in the other table [new table]. Can you help me.

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

  UserDefine

  AutoGenerate

  AutoGenerate

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

The above is my column in one of my table now i want to make the column in two like UserDefine and Autogenerate column in different table

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

Like the above, help me thank you.

2条回答
Viruses.
2楼-- · 2019-06-06 21:03

I would use two inserts, one for the "UserDefine" value and another one for the "AutoGenerate"

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

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

Changing the where clause to the apropiate conditions to discriminate between the two types.

查看更多
爷的心禁止访问
3楼-- · 2019-06-06 21:10

Try this:

;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

查看更多
登录 后发表回答