简体   繁体   English

如何使用UNION添加两个不同查询的结果

[英]How to add the results of two different queries with UNION

I have these two queries: 我有以下两个查询:

SELECT SUM(H) FROM stats_2017
UNION
SELECT SUM(H) FROM my_career_stats;

The first query gives a result of 70 and the second gives the result of 713. I want the sum of 70 and 713 but have not been able to get it. 第一个查询给出的结果为70,第二个查询给出的结果为713。我想要70和713的总和,但无法获得它。 Do you have any suggestions? 你有什么建议吗?

SELECT sum(a)
FROM (
  SELECT sum(h) as a FROM stats_2017
  UNION SELECT sum(h) as a FROM my_career_stats) as tmptbl

Explain: 说明:

You do your two queryes inside of the from of another select. 您可以在另一个选择的from中进行两个查询。 With that, you can sum both results. 这样,您可以将两个结果相加。

You got two rows already. 您已经有两行。 Now sum them: 现在总结一下:

SELECT sum(sum_) as total FROM 
  (
    SELECT SUM(H) as sum_ FROM stats_2017 
    UNION 
    SELECT SUM(H) as sum_ FROM my_career_stats
  ) sum_table

Your union query would end up giving you two records, one record per sum. 您的联合查询最终将给您两条记录,每笔款项一条记录。 Because you are selecting only a single value, you can omit the GROUP BY clause. 因为只选择一个值,所以可以省略GROUP BY子句。 I used the SUM() function and added it to a similar statement using an inline subquery. 我使用了SUM()函数,并将其添加到使用内联子查询的类似语句中。

SELECT SUM(H) + (SELECT SUM(H) FROM my_career_stats)
FROM stats_2017

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM