在“选择查询”的结果集中添加行

时间:2017-01-24 12:38:06

标签: sql sql-server sql-server-2008

我正在努力实现以下目标 例如

这就是我的......

  Name     Amount
  AAA        15
  AAA        20
  CCC        30
  CCC        50

这就是我想要的

  Name     Amount
  AAA        15
  AAA        20
             35     --(want to insert row which display sum of 1st & 2nd rows)
  CCC        30
  CCC        50 
             80      --(want to insert row which display sum of 3rd & 4th rows)

3 个答案:

答案 0 :(得分:2)

如果您只是按名称查找行摘要,则可以使用union,group by和order by:

DECLARE @tbl TABLE (Name char(3), Amount int)

insert @tbl
VALUES 
 ('AAA',15)
,('AAA',20)
,('CCC',30)
,('CCC',50)


select Name, Amount
FROM @tbl

UNION ALL

SELECT Name, SUM(Amount)
FROM @tbl GROUP BY Name

ORDER BY Name

对于使用子查询和CTE的工作示例(仅用作实际表的示例替换),请执行以下操作:

with vals as
(
    select 'aaa' as Name, 15 as Amount
    union all
    select 'aaa' as Name, 10 as Amount
    union all
    select 'bbb' as Name, 20 as Amount
    union all
    select 'bbb' as Name, 30 as Amount
    union all
    select 'bbb' as Name, 50 as Amount
)
select *
from
(
    select 'Amount' as ValType, Name, Amount
    from vals
    union all
    select 'Total' as ValType, Name, sum(Amount)
    from vals
    group by Name
)
order by Name, ValType
;

这将按Name列分组,并在子查询中求和,然后使用手动添加的ValType标识符列对输出进行排序。

答案 1 :(得分:0)

我使用UNION

完成了这项工作
SELECT * FROM 
(SELECT * FROM (VALUES ('AAA',15),
                      ('AAA',20),
                      ('CCC',30),
                      ('CCC',50)) CT (NAME,AMOUNT)


UNION ALL

SELECT NAME+' '+ 'Total' as Tot ,SUM(AMOUNT) FROM (VALUES ('AAA',15),
                      ('AAA',20),
                      ('CCC',30),
                      ('CCC',50)) CT (NAME,AMOUNT)                      
GROUP BY NAME+' '+ 'Total') X

答案 2 :(得分:-1)

我建议2 选择,然后使用 union all 加入

Select name, amount from table
union all
select '' as total, sum(amount) from table