我在SQL中创建了一个表,我正在尝试检索一个ROW,它返回值列中所有行的总和,并命名描述值' Total'。这是在存储过程中完成的吗?
EX:表1
Column1 Column2 Desc ValueColumn
1 6/30/14 One 11.1
2 6/30/14 Two 10.2
3 6/30/14 Three 9.0
我希望表结束如下: 表1
Column1 Column2 Desc ValueColumn
1 6/30/14 One 11.1
2 6/30/14 Two 10.2
3 6/30/14 Three 9.0
4 6/30/14 Total 30.3
你能帮忙解决一下这个问题吗?
谢谢。
答案 0 :(得分:1)
这是一个sql语句,可以满足您的要求:
SELECT Column1, Column2, Desc, ValueColumn
FROM
(
SELECT 1 as rolluporder, Column1, Column2, Desc, ValueColumn
FROM TABLE
UNION ALL
SELECT 2 as rolluporder, null as Column1, null as Column2,
'Total' AS Desc, SUM(ValueColumn) as ValueColumn
FROM TABLE
) T
ORDER BY rolluporder, Column1
这看起来有点不同但我希望这是你真正想要的:
Column1 Column2 Desc ValueColumn
1 6/30/14 One 11.1
2 6/30/14 Two 10.2
3 6/30/14 Three 9.0
null null Total 30.3
答案 1 :(得分:0)
DECLARE @IDC AS INT
SET @IDC = (
SELECT TOP 1 Column1
FROM [yourtable]
ORDER BY 1 DESC
)
SELECT *
FROM [yourtable]
UNION ALL
SELECT @IDC, Column2, 'Total', SUM(ValueColumn)
FROM [yourtable]
GROUP BY Column2