和联合值

时间:2018-02-08 15:18:09

标签: sql amazon-redshift

我想在UNION中总结两个值。喜欢:

SELECT
       sum(target_value) FROM table
UNION ALL
SELECT 
       sum(target_value) FROM table_2

但我不想得到2个和值,而是希望它们也可以求和。

我应该怎么做呢?

3 个答案:

答案 0 :(得分:0)

您可以尝试在子查询中使用它,并在外部查询中进行计算。确保使用UNION ALL来逃避重复检查

SELECT SUM(a) target_value
FROM
(SELECT
       sum(target_value) a FROM table
UNION ALL
SELECT 
       sum(target_value) a FROM table_2) ;

答案 1 :(得分:0)

您可以使用WITH子句执行此操作:

WITH CTE AS (SELECT SUM(target_value) as FirstSum 
             FROM table
             UNION
             SELECT 
             SUM(target_value) as FirstSum 
             FROM table_2)

SELECT SUM(FirstSum) AS TotalSum FROM CTE

答案 2 :(得分:0)

请参阅以下示例:

create table #temp (x int)
create table #temp2 (x2 int)

insert into #temp values (2)
insert into #temp values (3)

insert into #temp2 values (5)
insert into #temp2 values (6)

select t.col1,t.col2,t.col1+t.col2 as Total 
from (
        SELECT (select sum(x) FROM #temp) as col1,
               (select sum(x2) FROM #temp2) as col2
     ) t
相关问题