简体   繁体   English

如何在同一个查询中添加两个选择命令的结果

[英]How to add results of two select commands in same query

I currently have two select commands as per below.我目前有两个选择命令,如下所示。 What I would like to do is to add the results together in the SQL query rather than the variables in code.我想做的是将结果添加到 SQL 查询中,而不是代码中的变量。

select sum(hours) from resource;
select sum(hours) from projects-time;

Is it possible to have both in the same SQL and output a sum of both results?是否可以在同一个 SQL 中同时输出两个结果的总和?

Yes.是的。 It is possible :D有可能:D

SELECT  SUM(totalHours) totalHours
FROM
        ( 
            select sum(hours) totalHours from resource
            UNION ALL
            select sum(hours) totalHours from projects-time
        ) s

As a sidenote, the tablename projects-time must be delimited to avoid syntax error.作为旁注,必须分隔 tablename projects-time以避免语法错误。 Delimiter symbols vary on RDBMS you are using.分隔符因您使用的 RDBMS 而异。

Something simple like this can be done using subqueries in the select clause:可以使用select子句中的子查询来完成这样的简单操作:

select ((select sum(hours) from resource) +
        (select sum(hours) from projects-time)
       ) as totalHours

For such a simple query as this, such a subselect is reasonable.对于这样一个简单的查询,这样的子选择是合理的。

In some databases, you might have to add from dual for the query to compile.在某些数据库中,您可能必须添加from dual才能编译查询。

If you want to output each individually:如果要单独输出每个:

select (select sum(hours) from resource) as ResourceHours,
       (select sum(hours) from projects-time) as ProjectHours

If you want both and the sum, a subquery is handy:如果你想要两者总和,子查询很方便:

select ResourceHours, ProjectHours, (ResourceHours+ProjecctHours) as TotalHours
from (select (select sum(hours) from resource) as ResourceHours,
             (select sum(hours) from projects-time) as ProjectHours
     ) t

UNION ALL once, aggregate once: UNION ALL一次,聚合一次:

SELECT sum(hours) AS total_hours
FROM   (
   SELECT hours FROM resource
   UNION ALL
   SELECT hours FROM "projects-time" -- illegal name without quotes in most RDBMS
   ) x

Repeat for Multiple aggregations like:重复多个聚合,如:

SELECT sum(AMOUNT) AS TOTAL_AMOUNT FROM ( 
    SELECT AMOUNT FROM table_1
    UNION ALL 
    SELECT AMOUNT FROM table_2 
    UNION ALL 
    SELECT ASSURED_SUM FROM table_3
)

If you want to make multiple operation use如果要进行多项操作使用

select (sel1.s1+sel2+s2)

(select sum(hours) s1 from resource) sel1
join 
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2

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

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