1

We have two tables. One is PriceGroupTable and other is PricesTable. There is a one-to-many relationship between them. Please refer to the attached pic for more details.

enter image description here
I am looking for a SQL query which will give the result in the specific format which is highlighted in yellow in the attached pic.

Michael Green
25.3k13 gold badges54 silver badges100 bronze badges
asked Jun 14, 2015 at 8:12
4

1 Answer 1

1

Here is an example.

 Declare @PriceGroup TABLE
 ( id INT
 ,Catalog_Code INT
 ,Name VARCHAR(50)
 )
 INSERT INTO @PriceGroup (id,Catalog_Code,Name)
 VALUES (1,1,'PriceGroup1'),(2,1,'PriceGroup2'),(3,1,'PriceGroup3')
 Declare @Price TABLE
 (
 id INT
 ,articol_id INT
 ,catalog_code INT
 ,price_group_ID INT
 ,price DECIMAL(10,2)
 )
 INSERT INTO @Price (id,articol_id,catalog_code,price_group_ID,price)
 VALUES (89,57,1,1,11.01)
 ,(90,57,1,2,11.01)
 ,(91,58,1,3,11.01)
 ;WITH PriceSource
 AS (
 SELECT 
 articol_id
 ,Name
 ,price
 FROM
 @Price as P
 INNER JOIN @PriceGroup AS PG
 ON P.price_group_ID = PG.id
 AND P.catalog_code = PG.Catalog_Code 
 )
 SELECT *
 FROM PriceSource AS PS
 PIVOT
 ( MAX(Price)
 FOR Name IN ([PriceGroup1],[PriceGroup2],[PriceGroup3])
 )P

and the output:

articol_id PriceGroup1 PriceGroup2 PriceGroup3
57 11.01 11.01 NULL
58 NULL NULL 11.01
answered Jun 14, 2015 at 8:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.