I'm a SQL novice and tried my best to search for this topic before asking.
I have data in this format:
I need in this format:
I realize this is something probably very easy, but any help would be greatly appreciated.
Thanks!
You can use APPLY
if you are working with SQL Server
:
SELECT t.year, tt.Months, tt.Amount
FROM TABLE t CROSS APPLY
( VALUES (1, 'January', [Month1]),
(2, 'February', [Month2]),
. . .
) tt(seq, Months, Amount)
ORDER BY tt.seq, t.year;
You can try this on SQL SERVER:
CREATE TABLE TestPvt (Year varchar(32), January int, february int,
March int);
GO
INSERT INTO TestPvt VALUES ('Actual 2019',700,220,456);
INSERT INTO TestPvt VALUES ('Budget 2019',200,752,500);
SELECT Year, Month, Amount
FROM
(SELECT Year, January, february, March
FROM TestPvt) p
UNPIVOT
(Amount FOR Month IN
(January, february, March)
)AS unpvt;
The result is:
Year Month Amount
Actual 2019 January 700
Actual 2019 february 220
Actual 2019 March 456
Budget 2019 January 200
Budget 2019 february 752
Budget 2019 March 500
You could try: Taking the columns you provide i made this SQL, i hope this helps! Just change the table for the original
SELECT Year,
case when Month = 'Month1' then 'January'
when Month = 'Month2' then 'February'
when Month = 'Month3' then 'March'
else '' end as Month,
Amount
FROM
(SELECT Year, Month1, Month2, Month3
FROM [dbo].[ExampleMonths]) tb1
UNPIVOT
(Amount for Month IN
(tb1.Month1, tb1.Month2, tb1.Month3)
) AS uNp
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.