这段SQL语句要怎么精简一些?

wwooo 2008-09-26 06:24:48
 CREATE TABLE [dbo].[a] (
[department] [nvarchar] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[employee] [nvarchar] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[month] [nvarchar] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[purchase_id] [nvarchar] (10) COLLATE Chinese_PRC_CI_AS NULL)
-----------------------------------------------------------------------
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '1' , '001' , '01' , '0001' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '1' , '002' , '01' , '0002' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '1' , '002' , '01' , '0003' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '1' , '002' , '02' , '0004' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '1' , '001' , '02' , '0005' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '2' , '003' , '01' , '0006' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '2' , '003' , '01' , '0007' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '2' , '003' , '01' , '0008' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '2' , '003' , '02' , '0009' )
INSERT [a] ( [department] , [employee] , [month] , [purchase_id] ) VALUES ( '2' , '004' , '02' , '0010' )
--------------------------------------------
select a.num,b.num_of_dep,a.num/b.num_of_dep as rate from
(SELECT department,month,employee,count(*) as num
from a
group by department,month,employee) as a
join
(SELECT department,month,count(*) as num_of_dep
from a
group by department,month) as b
on a.department=b.department and a.month=b.month


结果如下:
1 3 0
2 3 0
1 2 0
1 2 0
3 3 1
1 2 0
1 2 0


问题有两个:
1 语句里面有两个子查询,不知如何精简?
2 rate要怎么设定是decimal(5,2)的数据类型
...全文
104 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
zheninchangjiang 2008-09-26
  • 打赏
  • 举报
回复
1-group by 不同,其他方法并无效率
2-cast(a.num/(b.num_of_dep*1.0) as numeric(5,2))

34,590

社区成员

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

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