Sql-server – separate data from one column to 2 columns

sql server

I have three columns viz Name, Value, Valueid.

I need to split the contents of value into two columns Valueof1 and Valueof2 based on the remaining two columns. Valueid has only two values either 1 or 2.

╔═══════╦═══════╦═════════╗
║ Name  ║ Value ║ Valueid ║
╠═══════╬═══════╬═════════╣
║ test1 ║   132 ║       1 ║
║ test2 ║   322 ║       2 ║
║ test3 ║   342 ║       1 ║
║ test1 ║   433 ║       2 ║
║ test2 ║   123 ║       1 ║
║ test3 ║   244 ║       2 ║
╚═══════╩═══════╩═════════╝

I'd like to see that data displayed like this:

╔═══════╦═══════╦═════════╦══════════╦══════════╗
║ Name  ║ Value ║ Valueid ║ Valueof1 ║ Valueof2 ║
╠═══════╬═══════╬═════════╬══════════╬══════════╣
║ test1 ║   132 ║       1 ║      132 ║      433 ║
║ test2 ║   322 ║       2 ║      123 ║      322 ║
║ test3 ║   342 ║       1 ║      342 ║      244 ║
║ test1 ║   433 ║       2 ║      132 ║      433 ║
║ test2 ║   123 ║       1 ║      123 ║      322 ║
║ test3 ║   244 ║       2 ║      342 ║      244 ║
╚═══════╩═══════╩═════════╩══════════╩══════════╝

Best Answer

sample data

;DECLARE @Data Table(Name  VARCHAR(20), Value INT, Valueid  INT
)
;INSERT INTO @Data
SELECT 'test1', 132, 1 UNION ALL
SELECT 'test2', 322, 2 UNION ALL
SELECT 'test3', 342, 1 UNION ALL
SELECT 'test1', 433, 2 UNION ALL
SELECT 'test2', 123, 1 UNION ALL 
SELECT 'test3', 244, 2

Sql script

;WITH CTE
AS
(
    SELECT Name,[1] AS Value1,[2] AS Value2 FROM
    (
    SELECT * FROM @Data
    ) AS SRC
    PIVOT
    (
    MAX(Value) FOR Valueid IN([1],[2])
    )
    AS Pvt
)

SELECT c.Name,
       d.Value,
       d.Valueid,
       c.Value1,
       c.Value2 
FROM CTE c
RIGHT Join @Data d
ON c.Name=d.Name

Expected Result http://rextester.com/AYGM10195

╔═══════╦═══════╦═════════╦══════════╦══════════╗
║ Name  ║ Value ║ Valueid ║ Valueof1 ║ Valueof2 ║
╠═══════╬═══════╬═════════╬══════════╬══════════╣
║ test1 ║   132 ║       1 ║      132 ║      433 ║
║ test2 ║   322 ║       2 ║      123 ║      322 ║
║ test3 ║   342 ║       1 ║      342 ║      244 ║
║ test1 ║   433 ║       2 ║      132 ║      433 ║
║ test2 ║   123 ║       1 ║      123 ║      322 ║
║ test3 ║   244 ║       2 ║      342 ║      244 ║
╚═══════╩═══════╩═════════╩══════════╩══════════╝