Home Ask Login Register

Developers Planet

Your answer is one click away!

sachinv February 2016

SQL Join query to join 2 tables to get desired output

I have 2 tables and need to join them to get a desired result. I tried multiple types of joins but no luck. Please assist.Below is how my tables looks like:

select * from t1

ProductId, Sequence, Property
100, 1, Size
100, 2, Folder
100, 3, License
101, 1, Usage
101, 2, Duration

select * from t2

SrNo, ProductId, Property, PropertyValue
1,    100, Size, 10GB
2,    100, Folder, /home/path
3,    101, Usage, Database

I need to join them to get the following result:

SrNo, ProductId, Sequence, Property, PropertyValue
1     100         1         Size      10GB
1     100         2         Folder    
1     100         3         License     
2     100         1         Size      
2     100         2         Folder    /home/path
2     100         3         License   
3     101         1         Usage      Database
3     101         2         Duration    

Below are the SQLs to reproduce the same tables:

create table t1 (ProductId INT, Sequence INT, Property VARCHAR(255))
insert into t1 values(100,1,'Size');
insert into t1 values(100,2,'Folder');
insert into t1 values(100,3,'License');
insert into t1 values(101,1,'Usage');
insert into t1 values(101,2,'Duration');

create table t2 (SrNo INT, ProductId INT, Property VARCHAR(255), PropertyValue VARCHAR(255))
insert into t2 values(1,100,'Size','10GB');
insert into t2 values(2,100,'Folder','/home/path');
insert into t2 values(3,101,'Usage','Database');

Please assist how can I write my query?


rohitreddyk February 2016

FROM t1 AS table1  
JOIN t2 AS table2 ON table1.ProductId = table2.ProductId

Hogan February 2016

Here you go

SELECT T2.SrNo, T2.ProductId, T1.Sequence, T1.Property, T3.PropertyValue
JOIN T1 ON T2.ProductID = T1.ProductID
LEFT JOIN T2 AS T3 ON T1.Property = T3.Property

The "problem" here is that you are treating T2 as two different tables. When I first select from T2 I'm only selecting SrNo and ProductId to get a list of these "valid" values. I then join them to T1. I then join back to T2 treating it as a lookup table for PropertyValue. Here I use a left join because not all combinations of Property and Sequence have a valid Property.

I "fixed" the code above based on the comment but a problem becomes clear. In your example you show

SrNo, ProductId, Sequence, Property, PropertyValue
1     100         1         Size      10GB
2     100         1         Size      

I don't know why the 2nd row does not have a PropertyValue of 10GB

Post Status

Asked in February 2016
Viewed 2,407 times
Voted 5
Answered 2 times


Leave an answer

Quote of the day: live life