两个查询的总和

时间:2011-07-13 20:53:10

标签: mysql sql aggregate-functions

我有两个基本查询,我需要总结:

Select hours, sum(hours) FROM table WHERE name='xxx' and Description='Worked'
Select hours2, sum(hours2) FROM table WHERE name='xxx' and Description2='Worked'

我已经尝试了UNION,它会得到每个查询的总数,但它不会合并它们。

表格设置为:

  • ID
  • 姓名
  • 小时
  • description
  • hours2
  • description2

我需要将小时与描述相关联,将小时2与描述2相关联,这就是为什么我有两个不同的查询。我需要总计小时和小时2的总和。

2 个答案:

答案 0 :(得分:24)

首先,你错过了group by,所以即使mysql没有抱怨它,你的hourshours2值也毫无意义。 其次,您UNION的结果可以放在派生子查询中,因此您将获得所需的总数:

SELECT SUM(hr) FROM
(
  Select sum(hours) as hr FROM table WHERE name='xxx' and Description='Worked'
  UNION ALL
  Select sum(hours2) as hr FROM table WHERE name='xxx' and Description2='Worked'
)a

答案 1 :(得分:2)

您需要将联合放入子查询中:

SELECT  Hours,
        SUM(Hours) AS Hours,
        SUM(Hours2) AS Hours2
FROM    (   SELECT  Hours,
                    SUM(Hours) AS Hours,
                    0 AS Hours2
            FROM    Table
            WHERE   Name = 'xxx'
            AND     Description = 'Worked'
            GROUP BY Hours
            UNION ALL
            SELECT  Hours2,
                    0 AS Hours,
                    SUM(Hours2) AS Hours
            FROM    Table
            WHERE   Name = 'xxx'
            AND     Description2 = 'Worked'
            GROUP BY Hours2
        ) t
GROUP BY Hours;