【发布时间】:2013-02-15 11:37:40
【问题描述】:
我目前有两个选择命令,如下所示。我想做的是将结果一起添加到 SQL 查询中,而不是代码中的变量。
select sum(hours) from resource;
select sum(hours) from projects-time;
是否可以在同一个 SQL 中同时输出两个结果的总和?
【问题讨论】:
我目前有两个选择命令,如下所示。我想做的是将结果一起添加到 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 而异。
【讨论】:
ALIAS。顺便问一下,你用的是什么RDBMS? RDBMS 代表关系数据库管理系统。 RDBMS is the basis for SQL,适用于所有现代数据库系统,如 MS SQL Server、IBM DB2、Oracle、MySQL 等...
projects-time。像这样,select sum(hours) totalHours from "projects-time"
可以使用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
【讨论】: