如何在postgres中进行减法

时间:2018-02-26 05:36:45

标签: sql postgresql

我有以下两个查询,一个是给我作为输出的总零件,另一个是给我总发送的零件作为输出。我的目标是获得将由“总零件 - 已发送零件”给出的总待处理零件。我将如何直接从查询中获得此结果。

代码:

--total parts

select
    dispatches.id,
    count(parts.id) as total_parts
from dispatch_projects,dispatches,parts 
where
    dispatches.id=dispatch_projects.dispatch_id and
    parts.project=dispatch_projects.project and
    parts.ignore=false and
    dispatch_projects.deleted = false and
    dispatches.created > now() - interval '15 days'
group by  dispatches.id
order by dispatches.id

--total dispatched parts




select
    dispatches.id,
    count(parts.id) as dispatched_parts
from dispatch_projects,dispatches,parts,boxes
where
    dispatches.id=dispatch_projects.dispatch_id and
    parts.project=dispatch_projects.project and
    parts.box_id=boxes.id and
    boxes.project=dispatch_projects.project and
    parts.ignore=false and
    dispatch_projects.deleted = false and
    dispatches.created > now() - interval '15 days'
group by  dispatches.id
order by dispatches.id

2 个答案:

答案 0 :(得分:1)

我们可以在单个查询中实现您想要的结果。

感谢您的第二个查询与第一个查询的不同之处在于对boxes表的额外连接。因此,术语count(parts.id)实际上计算了第一个查询中的部件数,现在将计算第二个查询中的框数。但是,我们仍然可以通过count(distinct parts.id)获取第二个查询中的总计部分。这是有效的,因为它会忽略由于加入boxes表而可能发生的部分重复。请考虑以下查询:

SELECT
    d.id,
    COUNT(DISTINCT p.id) - COUNT(p.id) as result
FROM dispatch_projects dp
INNER JOIN dispatches d
    ON d.id = dp.dispatch_id
INNER JOIN parts p
    ON p.project = dp.project
INNER JOIN boxes b
    ON p.box_id = b.id AND
       b.project = dp.project
WHERE
    p.ignore = false AND
    dp.deleted = false AND
    d.created > now() - INTERVAL '15 days'
GROUP BY
    d.id
ORDER BY
    d.id;

请注意,我已使用显式内部联接替换了逗号分隔的联接。这被认为是首选语法。

答案 1 :(得分:0)

您可以将它们放在公用表表达式中,然后计算从tmp_total_partstmp_total_dispatched_parts加入dispatches.id值之间的联接中选择的total_parts和total_dispatched部分之间的差异。

WITH tmp_total_parts AS (
    -- your total_parts query
),

tmp_total_dispatched_parts AS (
    -- your total_dispatched_parts query
),

select 
     id
    ,total_parts - dispatched_parts
from tmp_total_parts
join tmp_total_dispatched_parts
    on tmp_total_parts.id = tmp_total_dispatched_parts.id