获取联合查询返回的列的总和

时间:2015-11-18 08:43:40

标签: postgresql

select count(a.serial_no) from tra_2 a where a.model_no = 'KB123' and a.flag = '3'
union
select count(a.serial_no) from stock a where a.model_no = 'KB123' and a.trans_id is  NULL

作为输出,我将得到像

这样的结果
  4
  1

现在我需要总和4和1

输出应该是

  5

1 个答案:

答案 0 :(得分:1)

SELECT sum(serial_no)
FROM (
    SELECT count(a.serial_no)
    FROM tra_2 a
    WHERE a.model_no = 'KB123'
        AND a.flag = '3'

    UNION

    SELECT count(a.serial_no)
    FROM stock a
    WHERE a.model_no = 'KB123'
        AND a.trans_id IS NULL
    ) t -- alias

SELECT (
        SELECT count(a.serial_no)
        FROM tra_2 a
        WHERE a.model_no = 'KB123'
            AND a.flag = '3'
        ) + (
        SELECT count(a.serial_no)
        FROM stock a
        WHERE a.model_no = 'KB123'
            AND a.trans_id IS NULL
        ) AS total