两个查询的总数 [英] Sum totals of two queries
问题描述
我有两个基本查询,我需要对它们的总数求和:
I have two basic queries which I need to sum the totals of:
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,它将为我提供每个查询的总数,但不会将它们组合在一起.
I've tried UNION and it will get me the totals of each query but it will not combine them.
表格设置为:
- ID
- 名称
- 小时
- 说明
- hours2
- description2
我需要将小时和描述相关联,将小时2和描述2相关联,这就是为什么我有两个不同的查询的原因.我需要对小时数和小时数2进行总计.
I need to correlate hours to description and hours2 to description2 which is why I have the two different queries. I need to sum the totals of hours and hours2.
推荐答案
首先,您错过了group by
,因此,即使mysql没有抱怨,您的hours
和hours2
值也没有意义.
其次,您可以将UNION
的结果放入派生子查询中,这样您将具有所需的总数:
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
这篇关于两个查询的总数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!