I would like to transform one Sql server table into another.
Original table
Period Date Portfolio Benchmark
Pre0Month 12/31/2014 -0.0001 -0.0025
Pre1Month 11/31/2014 0.0122 0.0269
Pre2Month 10/31/2014 0.0176 0.0244
After transformation
Returns Pre0Month Pre1Month Pre2Month
Portfolio -0.0001 0.0122 0.0176
Benchmark -0.0025 0.0269 0.0244
Considering the name of the table to be MyTable, you can pivot it the following way:
SELECT * FROM
(
SELECT Period, [Returns], value
FROM MyTable
CROSS APPLY
(
SELECT 'Portofolio', CAST(Portofolio as varchar(10))
UNION ALL
SELECT 'Benchmark', CAST(Benchmark as varchar(10))
) c([Returns], value)
) d
PIVOT
(
MAX(value)
FOR Period IN (Pre0Month, Pre1Month, Pre2Month)
) piv;
This requires a combination of PIVOT and UNPIVOT:
DECLARE @t TABLE(period VARCHAR(32),[date] DATETIME, portfolio DECIMAL(28,4), benchmark DECIMAL(28,4));
INSERT INTO @t(period,[date],portfolio,benchmark)VALUES('Pre0Month','2014-12-31',-0.0001,-0.0025);
INSERT INTO @t(period,[date],portfolio,benchmark)VALUES('Pre1Month','2014-11-30',0.0122,0.0269);
INSERT INTO @t(period,[date],portfolio,benchmark)VALUES('Pre2Month','2014-10-31',0.0176,0.0244);
SELECT
*
FROM
(
SELECT
*
FROM
(
SELECT
period,
portfolio,
benchmark
FROM
@t
) AS t
UNPIVOT(
value
FOR Returns IN (portfolio,benchmark)
) AS up
) AS t
PIVOT(
MAX(value)
FOR period IN ([Pre0Month],[Pre1Month],[Pre2Month])
) AS p;
Result is the following:
Returns Pre0Month Pre1Month Pre2Month
benchmark -0.0025 0.0269 0.0244
portfolio -0.0001 0.0122 0.0176
Because you are using SQL-Server you can use the pivot command to do what you want. check it out here: https://technet.microsoft.com/en-us/library/ms177410%28v=sql.105%29.aspx
You can use the DateDiff function to separate the dates out by month easily too. https://msdn.microsoft.com/en-us/library/ms189794.aspx
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.