如何减去第一个查询和第二个查询的结果

How to subtract result of first query and second query

我想过滤掉从两个不同查询获得的结果并获得总计数。以下是我的两个查询:

    Query 1
    select count(*) 
    from table1 oow
    where oow.status='completed'--134 records

    Query 2
    select count(*) 
    from table2 oow 
    join #temp re
    on oow.order=re.order
    where oow.status='completed'--77 records

想要的结果是两者相减即134-77=57。 我如何在 sybase 中实现它。

试试这个:

SELECT
        (select count(*) 
        from table1 oow
        where oow.status='completed')
        -
        (select count(*) 
        from table2 oow 
        join #temp re
        on oow.order=re.order
        where oow.status='completed')

使用Cross Join

SELECT fst - scd
FROM   (SELECT Count(*) AS fst
        FROM   table1 oow
        WHERE  oow.status = 'completed'),--134 records
       (SELECT Count(*) AS scd
        FROM   table2 oow
               JOIN #temp re
                 ON oow.ORDER = re.ORDER
        WHERE  oow.status = 'completed') 

试试这个:

select count(*)
from table1
where not exists
(select 1 
from #temp re
where re.order = order and status = 'Completed')

此查询只是returns那些存在于table1但不存在于#temp中的行,基于顺序值和过滤条件。所以,上面相当于得到了总计数,过滤计数以及两者的差值。

鉴于 table 别名 oow 我将假设查询 1 中的 table1 和查询 2 中的 table2 实际上是相同的 table。如果是这样的话,你可以这样做:

select count(*) 
from 
    table2 oow 
    left join #temp re
        on oow.order=re.order
where oow.status='completed' 
    and re.order is null

我使用了左连接和空值检查,而不是执行减法。