SQL从当前列添加Total行

时间:2018-04-16 18:03:02

标签: sql sql-server sum

尝试从现有的Weekly_Total列添加Grand Totals的摘要行 - (这来自临时表,而不是重要的) -

SELECT
Rep, Monday, Tuesday, Wednesday, Thursday, Friday, Weekly_Total
FROM #bl_reptemp3

返回: these results

我只想在Weekly_Total下添加一行,加上该列的总和 - 似乎无法弄明白。

4 个答案:

答案 0 :(得分:1)

SELECT SUM(columnName)

是如何获得总计

所以......

INSERT INTO table (columns, go, here) SELECT 'value', 'val', SUM(here) FROM table 

您只需要一个简单的INSERT SELECT语句。

答案 1 :(得分:1)

SELECT
Rep, Monday, Tuesday, Wednesday, Thursday, Friday, Weekly_Total
FROM #bl_reptemp3

UNION

SELECT
Null Rep, Null Monday, NULL Tuesday, Null Wednesday, Null Thursday, NULL Friday, 
SUM(Weekly_Total) Weekly_Total
FROM #bl_reptemp3

答案 2 :(得分:-1)

您不需要在此处使用Aggregate,只需添加列

即可
Select Rep, Monday,Tuesday,Wednesday,Thursday,Friday,
         Monday+Tuesday+Wednesday+Thursday+Friday As weekly_total
from Mytable

如果列

中有空值
use isnull(monday,0)

答案 3 :(得分:-2)

在SQL Server中添加总行的方法是使用WITH ROLLUP。它看起来不像您的查询正在进行任何聚合,因此您可能需要将其添加到填充临时表的查询中。

SELECT some_value, SUM(some_other_value) AS summed_value
FROM your_table
GROUP BY some_value
WITH ROLLUP