一个简单的查询问题,顶者有分
IDNamevalue
1A1.0
2A2.0
3B15.0
4B12.0
5A25.0
用一个SQL语句,查出Name为A和B的Value的和,结果如下:
NameValue
A28.0
B27.0
小计55.0
我知道可以用
select distinct name,sum(value) as value from a group by name
但是这样只能列出
NameValue
A28.0
B27.0
下面的
小计55.0
怎么样出来,多谢指点啊。
顶折有分。
[解决办法]
先顶
[解决办法]
select isnull(name,'小计') name,sum(value) valuefrom tbgroup by namewith rollup
[解决办法]
select name,sum(value) as valuesfrom tbgroup by nameunion allselect '小计',sum(value) as valuesfrom tb
[解决办法]
select isnull(Name,'小计') as Name,sum(value) as valuefrom 表group by Name with rollup
[解决办法]
select name,sum(value) valuefrom tbgroup by nameunion allselect '小计' name,sum(value) valuefrom tb
[解决办法]
declare @t table(ID int,Name varchar(10),value numeric(4,1)) insert into @t values(1,'A',1.0 )insert into @t values(2,'A',2.0 )insert into @t values(3,'B',15.0) insert into @t values(4,'B',12.0) insert into @t values(5,'A',25.0) select isnull(Name,'小计') as Name,sum(value) as valuefrom @tgroup by Name with rollup/*Name value ---------- ---------------------------------------- A 28.0B 27.0小计 55.0*/
[解决办法]
create table tb(ID int, Name varchar(101),value numeric(10,1))insert into tbselect 1, 'A', 1.0 union allselect 2, 'A', 2.0 union all select 3, 'B', 15.0 union all select 4, 'B', 12.0 union all select 5, 'A', 25.0 select case when (grouping(name)=1) then '合计' else isnull(name,'unknow') end as name,sum(value) as value from tb group by name with cube /*name value-----------------A 28.0B 27.0合计 55.0*/drop table tb