Reputation:
I have a table report_card
and,
Sample data as below.
report_id orig_id test_id name address
------------------------------------------------------
1 JH06E IN2001 xyz delhi
2 HL789 IN2001 abc mumbai
3 ZPYNR IN2002 pqr mumbai
4 5R4HJ IN2002 mno delhi
and I want result like to get all the rows of mumbai but address is delhi instead of mumbai ? here I have id 1 and 2 have same test_id and 3 and 4 have also. Output like below,
report_id orig_id test_id name address
------------------------------------------------------
2 HL789 IN2001 abc delhi
3 ZPYNR IN2002 pqr delhi
Upvotes: 0
Views: 58
Reputation: 14666
A self join like:
SELECT t1.report_id, t1.orig_id, t1.test_id, t1.name, t2.address
FROM report_card t1
JOIN report_card t2
ON t1.test_id = t2.test_id
WHERE
t1.address = 'mumbai' AND
t2.address = 'delhi'
Upvotes: 2
Reputation: 17943
What @danblack have written is correct, but to select the orig_id
of mumbai you need to write your select like following.
SELECT t1.report_id,
t2.orig_id,
t1.test_id,
t1.name,
t1.address
FROM mytable t1
INNER JOIN mytable t2
ON t1.test_id = t2.test_id
WHERE t1.address = 'delhi'
AND t2.address = 'mumbai'
Edit :
sorry here i change my result on question, can i get all the rows of mumbai but address is delhi instead of mumbai
You can also do it using subquery like following.
SELECT t1.report_id,
t1.orig_id,
t1.test_id,
t1.name,
(SELECT address
FROM mytable m
WHERE m.test_id = t1.test_id
AND m.address = 'delhi'
LIMIT 1)AS address
FROM mytable t1
WHERE t1.address = 'mumbai'
But looking at your data and the expected result, you just need like following
SELECT t1.report_id,
t1.orig_id,
t1.test_id,
t1.name,
'delhi' address
FROM mytable t1
WHERE t1.address = 'mumbai'
Upvotes: 2