Skip to content
Advertisement

SQL only show orders with one order row. if more rows don display anything

i´m trying to search for orders with one specific article on the order row, but if there more than one row i don´t want to see any of the rows.

This is a sample of two orders where i only want to get one resault. order 9891026 has two rows and 9891025 only have one row.

    select  order_no, line_no
    from customer_order_line
    where order_no in('9891026','9891025')

result

order_no line_no
9891026 1
9891026 2
9891025 1

i only want to get

order_no line_no
9891025 1

I have don´t have a clue how to make the right query for this.

Advertisement

Answer

First find the single-line order numbers order_no (the subquery) and then select from orders with these order numbers only. Please note that a join query (though maybe harder to read) might be more efficient.

select * 
from customer_order_line 
where order_no in
(
 select order_no 
 from customer_order_line
 group by order_no 
 having count(*) = 1
) -- this is the list of single-item orders
and order_no in (9891026,9891025) -- this is the list of target orders
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement