如何在MySQL中使用UNION时添加值?

时间:2016-06-21 14:52:34

标签: mysql

我有这个查询,我尝试联合两个查询,因为每个部分都有不同的过滤器:

(/*First part where I want the current projects*/
SELECT p1.tipo as Tipo, COUNT(p1.tipo) AS Quantity
FROM projects AS p1
WHERE status IN ('REI','PRO')
GROUP BY Tipo
)
UNION
(/*Second part where I want those projects finished in the last year*/
SELECT p2.tipo as Tipo, COUNT(p2.tipo) AS Quantity
FROM projects AS p2
WHERE status IN ('TER')
AND COALESCE(p2.fech_fin,p2.fech_termino,p2.fech_proptermino) BETWEEN '2015-08-01' AND '2016-08-01'
GROUP BY Tipo
)

我得到以下结果:

Type Quantity
COL, 97
IND, 147
COL, 16
IND, 31

我看到我将结果与每个部分分开。如何才能像这样添加这些结果

Type Quantity
COL, 113
IND, 178

2 个答案:

答案 0 :(得分:2)

总结一下:

SELECT t.tipo,sum(t.quantity) as qty
    FROM (
    SELECT p1.tipo as Tipo, COUNT(p1.tipo) AS Quantity
    FROM projects AS p1
    WHERE status IN ('REI','PRO')
    GROUP BY Tipo
    UNION
    SELECT p2.tipo as Tipo, COUNT(p2.tipo) AS Quantity
    FROM projects AS p2
    WHERE status = 'TER'
    AND COALESCE(p2.fech_fin,p2.fech_termino,p2.fech_proptermino) BETWEEN '2015-08-01' AND '2016-08-01'
    GROUP BY Tipo
    ) t
GROUP BY t.tipo

虽然看起来如此,但您只需要一个查询:

    SELECT p1.tipo as Tipo, COUNT(p1.tipo) AS Quantity
    FROM projects AS p1
    WHERE p1.status IN ('REI','PRO') OR
          (p1.status = 'TER'
           AND COALESCE(p1.fech_fin,p1.fech_termino,p1.fech_proptermino) BETWEEN '2015-08-01' AND '2016-08-01')
    GROUP BY Tipo

答案 1 :(得分:1)

UNION只是将两个+不同的查询粘合到一个结果集中。你不能做"交叉联盟"使用单个查询进行聚合。您必须使用外部查询包装联合:

SELECT sum(foo)
FROM (
    SELECT somefield AS foo FROM ...
    UNION ALL
    SELECT otherfield AS foo FROM ...
) AS x