Union ALL的总和?可能吗?

时间:2018-03-13 01:46:06

标签: sql sum sql-server-2016 union-all

我如何能够将所有人联合起来? 基本上,我有一张表,上面有2行。现在我想要 加上 第3行,其中我想在第一行和一个字段SUM SUM字段 的 第二行并将两个SUM结果显示在第三行, 就像 查询(不创建新表)。我试过UNION,但这给了 一个 错误。

Date Type                     Orders         TOTAL
13/03 Sales Order             300            15000
13/03 Invoice                 200            10000

-------------我想添加第三行以获得总计1500和1000 ------

(How can I get this value of 25000) as a field?
是的,我已经应用了union all以获得上面的2行。但是,如果我想添加第三行怎么样?这是否意味着我必须再安装另一个UNION?

2 个答案:

答案 0 :(得分:1)

也许这就是你想要做的事情:

select Date, Type, Orders, TOTAL
from
(
    select Date, Type, Orders, TOTAL, 1 AS pos
    from t
    union all
    select NULL, NULL, NULL, sum(total), 2
    from t
) t
order by pos;

答案 1 :(得分:1)

尝试将select包装到数据集中并对所需的字段求和。

SELECT SUM(value) as total from(
SELECT 'A2' as field2,'A3' as field3,'A' as name,100 as value 
UNION ALL 
SELECT 'B2' as field2,'B3' as field3,'B' as name,200 as value)
as tbl

UNION ALL总行...当然,如果你可以使用临时表来存储第一个结果,那么它会更快(如果你执行它,你会发现它非常慢)

SELECT 'A2' as field2,'A3' as field3,'A' as name,100 as value 
UNION ALL 
SELECT 'B2' as field2,'B3' as field3,'B' as name,200 as value
UNION ALL
SELECT 'C1' as field2,'C2' as field3, 'C' as name, SUM(value) as total from (
SELECT 'A2' as field2,'A3' as field3,'A' as name,100 as value 
UNION ALL 
SELECT 'B2' as field2,'B3' as field3,'B' as name,200 as value)
as tbl

如果您的查询是在存储过程中编写的,那么您可以按以下方式应用temptable

;WITH tmpTable
AS (
SELECT 'A2' as field2,'A3' as field3,'A' as name,100 as value 
UNION ALL 
SELECT 'B2' as field2,'B3' as field3,'B' as name,200 as value
)
SELECT * FROM tmpTable UNION ALL
SELECT 'C1' as field2,'C2' as field3, 'C' as name, SUM(value) as total from tmpTable