Sum totals of two queries

℡╲_俬逩灬. 提交于 2019-11-30 12:45:47

First of all, you missed group by, so even though mysql doesn't complain about it, you hours and hours2 values are meaningless. Secondly, you the result of UNION can be put in derived subquery, so you will have the desired total :

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

You would need to place your union into a subquery:

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!