I've seen this question, this and this, however these are not what I want.
Please, do not close my question as it is not duplicate. It is really important to me.
I've managed to pivot a table, but this is not desired result:
The desired result looks like this:
My sample data is(it is just an example as OperatorX
and OC
columns should be 50 times):
DECLARE @OperatorPrice TABLE (ID INT NOT NULL, OperatorId INT NULL, Price
NUMERIC(18,3) NULL, FName VARCHAR(50) NULL)
INSERT INTO @OperatorPrice (
ID, OperatorId, Price, FName
)
VALUES
(226, 996, 22954,'Operator1')
, (266, 1016, 79011.2, 'Operator3')
, (112, 1029, 14869, 'Operator4')
, (93, 1031, 10568.96, 'Operator5')
DECLARE @TR TABLE
(
ID INT NULL ,
Operator1 DECIMAL(18,3) NULL, OC1 DECIMAL(18,3) NULL, Operator2 DECIMAL(18,3) NULL,
OC2 DECIMAL(18,3) NULL, Operator3 DECIMAL(18,3) NULL, OC3 DECIMAL(18,3) NULL,
Operator4 DECIMAL(18,3) NULL, OC4 DECIMAL(18,3) NULL, Operator5 DECIMAL(18,3) NULL,
OC5 DECIMAL(18,3) NULL
)
Example code:
INSERT @TR
(ID ,
Operator1, OC1, Operator2, OC2, Operator3, OC3, Operator4, OC4,
Operator5, OC5)
SELECT ID ,
Operator1, OC1, Operator2, OC2, Operator3, OC3, Operator4, OC4,
Operator5, OC5
FROM
(SELECT Price, id, FName
FROM @OperatorPrice) AS SourceTable
PIVOT
(
sum(Price)
FOR FName IN (Operator1, OC1, Operator2, OC2, Operator3, OC3,
Operator4, OC4, Operator5, OC5)
) AS PivotTable
SELECT * FROM @TR
How can I insert data into OC
columns?