分组求出合计的问题??

zzxiaoma 2008-06-18 03:18:14
表a

ccode kind_big_bm
0001 01
0001 01
0001 02
0002 02
0003 01
0003 03

根据ccode和kind_big_bm分组求的数量结果为
0001 01 2
0002 02 1
0003 01 1
0003 03 1
现在需要在下面加个合计
结果
0001 01 2
0002 02 1
0003 01 1
0003 03 1
合计 5
这个应该怎么做
...全文
108 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
kk19840210 2008-06-18
  • 打赏
  • 举报
回复
create table #T (ccode varchar(4),kind_big_bm varchar(2))
insert into #T
select '0001','01' union all
select '0001','01' union all
select '0001','02' union all
select '0002','02' union all
select '0003','01' union all
select '0003','03'


select ccode,kind_big_bm,hj=count(1) from #t group by ccode,kind_big_bm
union all
select '合计','',count(1) from #t
order by ccode,kind_big_bm

ccode kind_big_bm hj
----- ----------- -----------
0001 01 2
0001 02 1
0002 02 1
0003 01 1
0003 03 1
合计 6

(6 行受影响)
zzxiaoma 2008-06-18
  • 打赏
  • 举报
回复


如果写成
select b.ccode,kind_big_bm,count(1) as num from sys_kind_small a,emergency_regi b,code_login_unit c
where a.kind_small_bm=b.kind_small_bm and b.ccode=c.ccode and
(c.ccode like '4107%' and c.ilevel=3 or b.ccode='4107000000')
group by b.ccode,kind_big_bm
union all
select '合计','',count(1) from sys_kind_small a,emergency_regi b,code_login_unit c
where a.kind_small_bm=b.kind_small_bm and b.ccode=c.ccode and
(c.ccode like '4107%' and c.ilevel=3 or b.ccode='4107000000')

不能按ccode排序
liangCK 2008-06-18
  • 打赏
  • 举报
回复
--> 测试数据: #T
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (ccode varchar(4),kind_big_bm varchar(2))
insert into #T
select '0001','01' union all
select '0001','01' union all
select '0001','02' union all
select '0002','02' union all
select '0003','01' union all
select '0003','03'

select isnull(ccode,'合计') ccode,kind_big_bm,COUNT(*) cnt
from #T
group by ccode,kind_big_bm
with rollup
having GROUPING(ccode)=1 or GROUPING(kind_big_bm)=0

/*
/*
ccode kind_big_bm cnt
----- ----------- -----------
0001 01 2
0003 01 1
0001 02 1
0002 02 1
0003 03 1
合计 6

(6 行受影响)
*/
*/
liangCK 2008-06-18
  • 打赏
  • 举报
回复
--> 测试数据: #T
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (ccode varchar(4),kind_big_bm varchar(2))
insert into #T
select '0001','01' union all
select '0001','01' union all
select '0001','02' union all
select '0002','02' union all
select '0003','01' union all
select '0003','03'

select ccode,kind_big_bm,COUNT(*) cnt
from #T
group by ccode,kind_big_bm
union all
select N'合计' as ccode,'',COUNT(*) cnt
from #T

/*
ccode kind_big_bm cnt
----- ----------- -----------
0001 01 2
0003 01 1
0001 02 1
0002 02 1
0003 03 1
合计 6

(6 行受影响)
*/
kk19840210 2008-06-18
  • 打赏
  • 举报
回复

select ccode,kind_big_bm,hj=count(1) from tba group by ccode,kind_big_bm
union all
select '合计','',count(1) from tba
-狙击手- 2008-06-18
  • 打赏
  • 举报
回复
with cube ,,,,,,,,,,,,,,,,,,,,,,,,,,,

34,838

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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