问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/13507592/table-column-split-to-two-columns-in-sql