41

我目前有两个选择命令,如下所示。我想做的是将结果一起添加到 SQL 查询中,而不是代码中的变量。

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

是否可以在同一个 SQL 中同时输出两个结果的总和?

4

5 回答 5

78

是的。有可能的:D

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

作为旁注,projects-time必须对表名进行分隔以避免语法错误。分隔符符号因您使用的 RDBMS 而异。

于 2013-03-01T03:04:45.223 回答
34

可以使用select子句中的子查询来完成类似这样的简单操作:

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

对于这样一个简单的查询,这样的子选择是合理的。

在某些数据库中,您可能必须添加from dual才能编译查询。

如果要单独输出每个:

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

如果你想要两者总和,子查询很方便:

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
于 2013-03-01T03:10:05.040 回答
10

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
于 2013-03-01T03:12:37.473 回答
0

重复多个聚合,例如:

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
)
于 2016-05-18T17:44:12.667 回答
-1

如果要进行多次操作,请使用

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
于 2017-07-25T10:11:49.310 回答