Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpivot pairs of associated columns to rows

I have a table with staggered article prices like this:

ArtNr   Amount1   Price1   Amount2   Price2   Amount3   Price3
--------------------------------------------------------------
4711          1      3.5         5      3.0        10      2.5
4712          1      5.0         3      4.5         5      4.0
4713          1      7.0        10      6.0       100      5.0

I want to transpose that into this structure:

ArtNr   Amount   Price
----------------------
4711         1     3.5
4711         5     3.0
4711        10     2.5
4712         1     5.0
4712         3     4.5
4712         5     4.0
...

Can this be done with PIVOT/UNPIVOT in T-SQL, or do I have to use UNION?

like image 705
Prefect73 Avatar asked Oct 19 '25 16:10

Prefect73


1 Answers

CROSS APPLY (VALUES is the easiest way to unpivot usually, especially with multiple columns

SELECT
  t.ArtNr,
  v.Amount,
  v.Price
FROM YourTable t
CROSS APPLY (VALUES
  (Amount1, Price1),
  (Amount2, Price2),
  (Amount3, Price3)
) v(Amount, Price)

Some more tricks you can do with CROSS APPLY

like image 80
Charlieface Avatar answered Oct 21 '25 06:10

Charlieface



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!