W de wee W de wee - 1 month ago 10
SQL Question

SQL query adding rows on result - sql server 2012

In my Order table I have for each Order three tasks (id_task). If an id_address matches id_address 14 then I want to show all the tasks of that specific id_order.

id_order | id_task | id_address
1 | 556 | 12
1 | 557 | 14
1 | 558 | 11
2 | 559 | 56
2 | 560 | 88
2 | 561 | 77


results when I match id_address = 14

id_order | id_task | id_address
1 | 556 | 12
1 | 557 | 14
1 | 558 | 11


How do I do this?

I do now:

select id_order, id_task, id_address
from order
where id_address = 14


Of course this doesn't work. I will only get task 557. But I also want to have the other results from id_order. But how?

Answer

Here is the simple solution:

select 
      id_order
    , id_task
    , id_address 
from 
    [order] 
where 
    id_order IN (
            select 
                id_order 
            from 
                [order] 
            where   
                id_address = 14)