我目前有两个选择命令,如下所示。我想做的是将结果一起添加到 SQL 查询中,而不是代码中的变量。
select sum(hours) from resource;
select sum(hours) from projects-time;
是否可以在同一个 SQL 中同时输出两个结果的总和?
是的。有可能的: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 而异。
可以使用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
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
重复多个聚合,例如:
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
)
如果要进行多次操作,请使用
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