SQL分类汇总

hzliuhai88 2013-06-05 12:40:26

如下数据:
ID DT SL
101 2013-02-01 3
101 2013-02-03 5
101 2013-02-05 3
102 2013-02-01 3
102 2013-02-01 3
需显示如下
ID DT SL
101 2013-02-01 3
101 2013-02-03 5
101 2013-02-05 3
合计:
102 2013-02-01 3
102 2013-02-03 3
合计: 6
...全文
128 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xxfvba 2013-06-05
  • 打赏
  • 举报
回复
select * from hz union all select ID,'合计',sum(sl) from hz group by ID order by ID,DT
唐诗三百首 2013-06-05
  • 打赏
  • 举报
回复

create table hz
(ID int, DT varchar(16), SL int)

insert into hz
 select 101, '2013-02-01', 3 union all
 select 101, '2013-02-03', 5 union all
 select 101, '2013-02-05', 3 union all
 select 102, '2013-02-01', 3 union all
 select 102, '2013-02-01', 3
 

select case when rn is not null then rtrim(ID)
            else '合计:' end 'ID',
       case when rn is null then '' else max(DT) end 'DT',
       sum(SL) 'SL'
from (select ID,DT,SL,
             row_number() over(partition by ID order by getdate()) 'rn' from hz) a 
group by ID,rn
with rollup
having grouping(ID)<>1

/*
ID           DT               SL
------------ ---------------- -----------
101          2013-02-01       3
101          2013-02-03       5
101          2013-02-05       3
合计:                          11
102          2013-02-01       3
102          2013-02-01       3
合计:                          6

(7 row(s) affected)
*/

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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