对表先排序 然后汇总某列

uiwq 2006-10-13 10:07:43
表 A

tem_name m_shu c_ti

name1 2 au
name2 12 ac
name3 20 as
name2 10 as
name1 25 av
name4 65 ak
name1 85 47





查询得到

tem_name m_shu c_ti

name1 2 au
name1 25 av
name1 85 47

name2 12 ac
name2 10 as
name3 20 as
name4 65 ak --排序没问题的


name1 112 --怎么得到 tem_name 中所有值为;name1对应 的m_shu列的和
name2 22 --同上 name2 的
name3 20
name4 65

//不知道有name1 name2 ……的存在,消除重复行后得到的就是所有要汇总的

大家帮忙,谢谢!







...全文
161 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
新鲜鱼排 2006-10-13
  • 打赏
  • 举报
回复
希望这个有用
http://community.csdn.net/Expert/topic/5073/5073353.xml?temp=.159466
allright_flash 2006-10-13
  • 打赏
  • 举报
回复
(select tem_name,m_shu from 表A
order by tem_name)
union all
(select tem_name,sum(m_shu) as m_shu from 表A
group by tem_name order by tem_name)
hellowork 2006-10-13
  • 打赏
  • 举报
回复
top 100 percent 可以省略
hellowork 2006-10-13
  • 打赏
  • 举报
回复
----创建测试数据
declare @t table(tem_name varchar(10), m_shu int, c_ti varchar(10))
insert @t
select 'name1', 2, 'au' union all
select 'name2', 12, 'ac' union all
select 'name3', 20, 'as' union all
select 'name2', 10, 'as' union all
select 'name1', 25, 'av' union all
select 'name4', 65, 'ak' union all
select 'name1', 85, '47'

----查询
select top 100 percent tem_name,m_shu,c_ti
from
(
select *,0 as sortid from @t
union all
select tem_name,sum(m_shu),'',1 from @t group by tem_name
) as t order by sortid,tem_name

/*结果
tem_name m_shu c_ti
---------------------------------------------
name1 2 au
name1 25 av
name1 85 47
name2 12 ac
name2 10 as
name3 20 as
name4 65 ak
name1 112
name2 22
name3 20
name4 65
*/
allright_flash 2006-10-13
  • 打赏
  • 举报
回复
select tem_name,m_shu from 表A
order by tem_name


select tem_name,sum(m_shu) from 表A
group by tem_name order by tem_name
allright_flash 2006-10-13
  • 打赏
  • 举报
回复
select tem_name,sum(m_shu) from 表A
group by tem_name order by tem_name
九斤半 2006-10-13
  • 打赏
  • 举报
回复
什么意思?

排序后的结果+汇总后的结果???
uiwq 2006-10-13
  • 打赏
  • 举报
回复
本意是想两个结果集合,能不能合在一起:)
sqlfan 2006-10-13
  • 打赏
  • 举报
回复
mark

22,210

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧