[英]Add row in result set of Select Query
I am trying achieve below eg.我正在尝试在下面实现,例如。
this is what I have ...这就是我所拥有的...
Name Amount
AAA 15
AAA 20
CCC 30
CCC 50
this is what I want这就是我要的
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)
If you're just looking for a summary of rows by name, you could use a union, and a group by, and an 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
For a working example using subquery and CTE (only used as an example replacement for the actual table), take the following:对于使用子查询和 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
;
This will group by the Name
column, and sum within a subquery, then sort the output using manually added ValType
identifier column.这将按
Name
列分组,并在子查询中求和,然后使用手动添加的ValType
标识符列对输出进行排序。
I have done this using UNION我已经使用 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
I suggest doing 2 selects and then use union all to join them我建议做 2 个选择,然后使用union all加入它们
Select name, amount from table
union all
select '' as total, sum(amount) from table
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.