复合求和:我想创建一个复合查询,它从两个不同的表中获取两列的单独总和,然后对它们求和
Posted
技术标签:
【中文标题】复合求和:我想创建一个复合查询,它从两个不同的表中获取两列的单独总和,然后对它们求和【英文标题】:Compound summation: I would like to create a compound query which gets the individual sum of two columns from two different tables and then sum them 【发布时间】:2021-11-03 18:20:06 【问题描述】:select sum(saved_amount - withdrawal_amount) from goal_withdrawal as sum1;
union
select suM(amount) from phone_verification as sum2;
select sum1 + sum2;
【问题讨论】:
【参考方案1】:您可以在 select 语句中使用 select 语句来获得所需的内容。 我已经制定了以下示例:
--Creating some fake-data
DECLARE @goal_withdrawal TABLE (saved_amount int, withdrawal_amount int);
INSERT INTO @goal_withdrawal VALUES (100,100);
INSERT INTO @goal_withdrawal VALUES (150,100);
INSERT INTO @goal_withdrawal VALUES (200,125);
DECLARE @phone_verification TABLE (amount int);
INSERT INTO @phone_verification VALUES (100);
INSERT INTO @phone_verification VALUES (150);
SELECT
(
SELECT (SUM(saved_amount) - SUM(withdrawal_amount))
FROM @goal_withdrawal
) AS sum1,
(
SELECT SUM(amount)
FROM @phone_verification
) AS sum2,
(
SELECT (SUM(saved_amount) - SUM(withdrawal_amount))
FROM @goal_withdrawal
)
+
(
SELECT SUM(amount)
FROM @phone_verification
) AS sum3
产生三列:
Sum1 为 125 Sum2 为 250 Sum3 为 375【讨论】:
以上是关于复合求和:我想创建一个复合查询,它从两个不同的表中获取两列的单独总和,然后对它们求和的主要内容,如果未能解决你的问题,请参考以下文章