Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
See the following scenario:

Tables for the question:
SQL
Table : T1
c10  c12
---  ----
e1   A
e2   B
e3   C

Table: T2

c1  c2  c3  c4  c5   C6
--- -- --- ---  ---  ---
1   P  e1  e2   null  X
2   Q  e3  null null  Y
3   R  e2  e1   null  X
4   S  e3  e1   e2    Z


The c3, c4 and c5 columns of T2 table depends on c12 column of T1 table.

I want the following output:


c1  c2  c3  c4  c5
--- -- --- ---  ---
1   P   A   B   null
2   Q   C  null null
3   R   B   A   null
4   S   C   A   B


Can you help me to write an SQL to retrieve the above output from the table T1 and T2?

The SQL may be like:
SQL
Select c1, c2, t1.c12 as c3....... from t1, t2 where join condition


But I am not getting the actual sql in my mind.
So please help me regarding this.
Posted
Comments
ProEnggSoft 19-Mar-12 13:20pm    
My 5! for nicely formulating the question.

1 solution

SQL
SELECT c1,c2,(SELECT TOP 1 c12 FROM T1 WHERE T1.c10=T2.c3) AS c3,
    (SELECT TOP 1 c12 FROM T1 WHERE T1.c10=T2.c4) AS c4,
    (SELECT TOP 1 c12 FROM T1 WHERE T1.c10=T2.c5) AS c5
FROM T2
-- If multiple values are expected in T1 table say
-- e1,A  e1,M  then ORDER BY clause can be used for greater
-- control on the value returned by sub query
SELECT c1,c2,(SELECT TOP 1 c12 FROM T1 WHERE T1.c10=T2.c3 ORDER BY T1.c12 DESC) AS c3,
    (SELECT TOP 1 c12 FROM T1 WHERE T1.c10=T2.c4 ORDER BY T1.c12) AS c4,
    (SELECT TOP 1 c12 FROM T1 WHERE T1.c10=T2.c5 ORDER BY T1.c10) AS c5
FROM T2
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900