Question

I have a list of orders with suboperations. How can I create a list of finished orders? Finished order must have finished all suboperations.

Table "orders":

order_no | suboperation | finished
1        | preparing    | 01/01/2009
1        | scrubbing    | 01/05/2009
1        | painting     | 01/10/2009
2        | preparing    | 02/05/09
2        | painting     | NULL
3        | preparing    | 03/01/2009
3        | scrubbing    | 03/15/2009
3        | painting     | 03/10/2009
4        | bending      | NULL
4        | crashing     | NULL
4        | staining     | NULL
4        | painting     | NULL

Desired output (finished orders):

order_no
1
3
Was it helpful?

Solution

You'll could also use count, group by and having. This avoids having to do any table joins which is more efficient.

create table #Orders (
    order_no int,
    suboperation varchar(30),
    finished smalldatetime)

insert into #Orders values (1 , 'preparing' , '01/01/2009')
insert into #Orders values (1 , 'scrubbing' , '01/05/2009')
insert into #Orders values (1 , 'painting' , '01/10/2009')
insert into #Orders values (2 , 'preparing' , '02/05/09')
insert into #Orders values (2 , 'painting' , NULL)
insert into #Orders values (3 , 'preparing' , '03/01/2009')
insert into #Orders values (3 , 'scrubbing' , '03/15/2009')
insert into #Orders values (3 , 'painting' , '03/10/2009')
insert into #Orders values (4 , 'bending' , NULL)
insert into #Orders values (4 , 'crashing' , NULL)
insert into #Orders values (4 , 'staining' , NULL)
insert into #Orders values (4 , 'painting' , NULL)

select 
    order_no, 
    count(1) As NoOfSubtasks --count(1) gives the number of rows in the group
    count(finished) As NoFinished, --count will not count nulls
from #Stuff
group by 
     order_no
having 
    count(finished) = count(1) --if finished = number of tasks then it's complete

drop table #Orders

OTHER TIPS

A good ol' WHERE NOT EXISTS clause ought to work here:

SELECT DISTINCT o.order_no
FROM orders o
WHERE NOT EXISTS (SELECT p.order_no
                  FROM orders p
                  WHERE p.order_no = o.order_no 
                  AND p.finished IS NULL)

I was trying to find a way to use the MIN function, and came up with this:

SELECT order_no

FROM Orders

GROUP BY order_no

HAVING (MIN(ISNULL(finished, 0)) <> 0)

null can be annoying...

not as performant, maybe, but easier for me to understand.

SELECT order_no, suboperation, finished
FROM orders o1
WHERE NOT EXISTS(
    SELECT 1 
        FROM orders o2 
        WHERE o1.order_no = o2.order_no 
        AND o2 IS NULL )
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top