I have a shippings table, with some general information about a shipment.I also got a components table with some general information about components.And I got a shippingscomposition table where it is defined what components and how much of them is used in which shipment.I would like a query where I get a column for each component.I assume I need a query with the PIVOT keyword, but I can't get it right. Any help appreciated! Thanks.
declare @Shippings Table (ShippingID int IDENTITY(1,1), ShippingName varchar(50));declare @ShippingComposition Table (ShippingCompositionID int IDENTITY(1,1), ShippingID int, ComponentID int, LoadingVolume int, DischargeVolume int);declare @Components Table(ComponentID int IDENTITY(1,1), ComponentName varchar(100));insert into @Componentsvalues('Component 1'),('Component 2'),('Component 3'),('Component 4'),('Component 5');insert into @Shippingsvalues('Shipping 1'),('Shipping 2'),('Shipping 3');insert into @ShippingComposition(ShippingID, ComponentID, LoadingVolume, DischargeVolume)values(1,1,100,10),(1,2,200,20),(1,3,300,30),(1,4,400,40),(1,5,500,50),(2,1,110,11),(2,3,330,33),(2,4,440,44),(2,5,550,55),(3,2,222,2),(3,3,333,3),(3,4,444,4);select Shippings.ShippingName, Components.ComponentName, ShippingComposition.LoadingVolume, ShippingComposition.DischargeVolumefrom @Shippings as Shippingsinner join @ShippingComposition as ShippingComposition on ShippingComposition.ShippingID = Shippings.ShippingIDinner join @Components as Components on Components.ComponentID = ShippingComposition.ComponentIDorder by Shippings.ShippingID, Components.ComponentID
expected result:
ShippingName Component 1 Loading Component 1 Discharge Component 2 Loading Component 2 Discharge Component 3 Loading Component 3 Discharge Component 4 Loading Component 4 Discharge Component 5 Loading Component 5 Discharge------------ ------------------- --------------------- ------------------- --------------------- ------------------- --------------------- ------------------- --------------------- ------------------- ---------------------Shipping 1 100 10 200 20 300 30 400 40 500 50Shipping 2 110 11 0 0 330 33 440 44 550 55Shipping 3 0 0 222 2 333 3 444 4 0 0