分组统计并排序的问题

march22 2005-12-27 04:32:31
数据表的字段格式如下:

row dept total date
--------------------------------
1 a部门 20 2005-06-02
2 b部门 12 2005-06-03
3 c部门 40 2005-06-20
4 a部门 21 2005-07-03
5 a部门 25 2004-12-21
6 b部门 58 2004-03-15
7 c部门 12 2005-07-08
8 c部门 55 2005-12-27
9 c部门 20 2005-11-21
10 a部门 42 2005-12-27
---------------------------------

现在需要按部门分组,统计年度数据,并且按年度统计数据的大小排序。
请帮我写出Sql语句,谢谢。
...全文
107 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
pclogic 2005-12-31
  • 打赏
  • 举报
回复
mark
zlp321002 2005-12-27
  • 打赏
  • 举报
回复
--测试环境
declare @t table(row int identity(1,1),dept varchar(10),total int,date datetime)
insert into @t select 'a部门',20,'2005-06-02'
union all select 'b部门',12,'2005-06-03'
union all select 'c部门',40,'2005-06-20'
union all select 'a部门',21,'2005-07-03'
union all select 'a部门',25,'2004-12-21'
union all select 'b部门',58,'2004-03-15'
union all select 'c部门',12,'2005-07-08'
union all select 'c部门',55,'2005-12-27'
union all select 'c部门',20,'2005-11-21'
union all select 'a部门',42,'2005-12-27'
--查询
select
dept=dept,
total=sum(total),
date=year(date)
from @t
group by dept,year(date)
order by dept asc,total desc
--结果
dept total date
---------- ----------- -----------
a部门 83 2005
a部门 25 2004
b部门 58 2004
b部门 12 2005
c部门 127 2005

(所影响的行数为 5 行)


子陌红尘 2005-12-27
  • 打赏
  • 举报
回复
declare @t table(row int,dept varchar(10),total int,date datetime)

insert into @t select 1 ,'a部门',20,'2005-06-02'
insert into @t select 2 ,'b部门',12,'2005-06-03'
insert into @t select 3 ,'c部门',40,'2005-06-20'
insert into @t select 4 ,'a部门',21,'2005-07-03'
insert into @t select 5 ,'a部门',25,'2004-12-21'
insert into @t select 6 ,'b部门',58,'2004-03-15'
insert into @t select 7 ,'c部门',12,'2005-07-08'
insert into @t select 8 ,'c部门',55,'2005-12-27'
insert into @t select 9 ,'c部门',20,'2005-11-21'
insert into @t select 10,'a部门',42,'2005-12-27'


select
a.dept,a.[year],total=sum(a.total)
from
(select dept,total,[year]=year(date) from @t) a
group by
a.dept,a.[year]
order by
a.dept,total desc


/*
dept year total
---------- ----------- -----------
a部门 2005 83
a部门 2004 25
b部门 2004 58
b部门 2005 12
c部门 2005 127
*/

34,873

社区成员

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

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