Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using MS SQL SERVER and I have following data:

ValDate Month CurID SpotRate_Cad
11/1/2016 11 cad 1.00000000
11/1/2016 11 usd 1.30000000
11/1/2016 11 eur 1.51000000
11/2/2016 11 cad 1.00000000
11/2/2016 11 usd 1.31000000
11/2/2016 11 eur 1.50000000

I would like to have this format

Date Month cad usd eur
11/1/2016 11 1.00000000 1.30000000 1.51000000
11/1/2016 11 1.00000000 1.31000000 1.50000000

What I have tried:

SELECT *
FROM (
SELECT npv.ValDate, month(npv.ValDate) as Month, rtrim(npv.CurID) as CurID, (npv.SpotRate) as SpotRate_Cad

FROM boss_bo.dbo.NPVPLFxRate as npv
LEFT JOIN boss_bo.dbo.NPVPLFxRate as npv2
ON (npv.ValDate =npv2.ValDate)

WHERE (npv.ValDate<='2017-06-20')
AND (npv.ValDate>='2016-11-01')
AND (npv2.CurID = "usd")
) fx

PIVOT (
ValDate, Month, SpotRate
FOR CurID IN
([cad], [usd], [eur])
) AS PVT
Posted
Updated 26-Jun-17 0:23am
Comments
Andy Lanng 26-Jun-17 3:21am    
Don't use pivot. What you want is not a function of pivot.
Kornfeld Eliyahu Peter 26-Jun-17 4:29am    
Do you always have a fixed number of currencies to merge?

1 solution

CREATE TABLE #thetable 
( id            INT IDENTITY(1,1) NOT NULL ,
ValDate         DateTime,
[Month]         INT,
CurID           CHAR(3),
SpotRate        FLOAT
)

INSERT INTO #thetable (ValDate, [Month], CurID, SpotRate) VALUES ('11/1/2016',11, 'cad', 1.0)
INSERT INTO #thetable (ValDate, [Month], CurID, SpotRate) VALUES ('11/1/2016',11, 'usd', 1.3)
INSERT INTO #thetable (ValDate, [Month], CurID, SpotRate) VALUES ('11/1/2016',11, 'eur', 1.51)
INSERT INTO #thetable (ValDate, [Month], CurID, SpotRate) VALUES ('11/2/2016',11, 'cad', 1.0)
INSERT INTO #thetable (ValDate, [Month], CurID, SpotRate) VALUES ('11/2/2016',11, 'usd', 1.31)
INSERT INTO #thetable (ValDate, [Month], CurID, SpotRate) VALUES ('11/2/2016',11, 'eur', 1.5)


SELECT * FROM #thetable

SELECT
   dateadd(day,datediff(day,0, t.ValDate ),0) as DATE
   ,[Month]
   ,SUM(cad) as cad
   ,SUM(usd) as usd
   ,SUM(eur) as eur
FROM
(
SELECT
  ValDate
  ,[Month]
  ,CASE WHEN CurID = 'cad' THEN SpotRate END AS 'cad'
  ,CASE WHEN CurID = 'usd' THEN SpotRate END AS 'usd'
  ,CASE WHEN CurID = 'eur' THEN SpotRate END AS 'eur'
FROM  #thetable
) t
GROUP BY 
dateadd(day,datediff(day,0, t.ValDate ),0)
,[Month]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900