SQL选择具有多个操作的已完成订单

时间:2009-08-05 16:29:17

标签: sql ms-access select jet

我有一个包含子操作的订单列表。如何创建已完成订单列表?完成订单必须完成所有子操作。

表“订单”:

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

期望的输出(已完成的订单):

order_no
1
3

4 个答案:

答案 0 :(得分:3)

您还可以使用计数分组拥有。这避免了必须进行任何更高效的表连接。

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

答案 1 :(得分:1)

一个好的'WHERE NOT EXISTS条款应该在这里工作:

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)

答案 2 :(得分:0)

我试图找到一种使用MIN功能的方法,并想出了这个:

SELECT order_no

FROM Orders

GROUP BY order_no

HAVING(MIN(ISNULL(已完成,0))<> 0)

null可能很烦人......

不是高效,也许,但我更容易理解。

答案 3 :(得分:-1)

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 )