I'm currently making a program to store data in database sql server. and the data is a cost that divided into max 5 column cost details. As for the first row it labeled with 1 and second with 2, up to 5 row with same id. So i'm making the table like the picture below. And Now i want to select the table from row to column like in the picture. i'm making the query like this. I get the result like i want, but the problem is that the query cost like 5/more times the execution plan by just selecting the same table. My question is, is there a way to make the result like in the picture just by selecting once the table or is there any other way to make like the result with better performance, i hear of using pivot for transposing row to column, but in my case i don't know how to do it. Thanks for reply
this is the execution plan https://www.brentozar.com/pastetheplan/?id=SJGJdaCB7
select * FROM TblKecelakaanBiaya;
with tbl AS (
select *, ROW_NUMBER() OVER(PARTITION by id_kasus ORDER BY id_kasus) rn FROM TblKecelakaanBiaya
)
SELECT A.id_kasus, A.ket_biaya1, A.jlh_biaya1, C.ket_biaya2, C.jlh_biaya2,
D.ket_biaya3, D.jlh_biaya3, E.ket_biaya4, E.jlh_biaya4, F.ket_biaya5, F.jlh_biaya5
FROM (SELECT id_kasus, ket_biaya ket_biaya1, jlh_biaya jlh_biaya1 FROM tbl WHERE rn = 1) A
LEFT JOIN (SELECT id_kasus, ket_biaya ket_biaya2, jlh_biaya jlh_biaya2 FROM tbl WHERE rn = 2) C ON A.id_kasus = C.id_kasus
LEFT JOIN (SELECT id_kasus, ket_biaya ket_biaya3, jlh_biaya jlh_biaya3 FROM tbl WHERE rn = 3) D ON A.id_kasus = D.id_kasus
LEFT JOIN (SELECT id_kasus, ket_biaya ket_biaya4, jlh_biaya jlh_biaya4 FROM tbl WHERE rn = 4) E ON A.id_kasus = E.id_kasus
LEFT JOIN (SELECT id_kasus, ket_biaya ket_biaya5, jlh_biaya jlh_biaya5 FROM tbl WHERE rn = 5) F ON A.id_kasus = F.id_kasus
The execution plan for query 1 is just 1% and the other one is 99%.