0

I got two rows from database based on particular id

ID         Address    Res_Address     Office_Address
-------------------------------------------------
4          C 60            0               1
4          D 90            1               0

I just want to select Address having flag res_address 1 in ResAddress And flag having Office_address 1 As OfficeAddress by select statement. I don't want to use stored procedure.

5
  • 3
    You might need to expand on this slightly. Why do you have two users with the same ID? Is it always Rahul as user1 and Vikram as user2, or could this change? Commented Jul 26, 2013 at 5:44
  • 1
    Agree that more details are needed. If it's just two, you could SELECT MAX(value) AS user1, MIN(value) AS user2 FROM <tablename> GROUP BY id. But this is kind of hacky. Commented Jul 26, 2013 at 5:46
  • You can take it like this.Actually ID is addressID. I will always get two rows in which one row will have office address of that person and other row will have residence address based on flag in rows. So i just want to select these two address that office address and residence address. Commented Jul 26, 2013 at 5:48
  • 1
    What RDBMS (MySql, SQL Server, Oracle, ...) are you using? Commented Jul 26, 2013 at 5:53
  • Provide more table content... Commented Jul 26, 2013 at 5:53

1 Answer 1

2

Try

SELECT ID,
       MIN(CASE WHEN Res_Address    = 1 THEN Address END) ResidentAddress,
       MIN(CASE WHEN Office_Address = 1 THEN Address END) OfficeAddress
FROM 
(
  SELECT -- your subquery that returns two rows goes here
) q
 GROUP BY ID

Sample output:

| ID | RESIDENTADDRESS | OFFICEADDRESS |
----------------------------------------
|  4 |            D 90 |          C 60 |

Here is SQLFiddle demo

UPDATE If I understand correctly your comment you can use COALESCE() for that

SELECT ID,
       COALESCE(MIN(CASE WHEN Res_Address = 1    THEN Address END), '0') ResidentAddress,
       COALESCE(MIN(CASE WHEN Office_Address = 1 THEN Address END), '0') OfficeAddress
FROM 
(
  SELECT * FROM Table1
) q
 GROUP BY ID

Here is SQLFiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

Just for addition if my query returns only one row. Having Res_Address and Ofc_Address as 0 and 0

Your Answer

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.