现在要统计出如下记录
部门名称,部门人数,销售单数,销售金额。
第一小组 5 50 50000
第二小组 7 80 120000
我想的是分组去统计,但这个应该要嵌入分组查询吧。就是select * from (select * from .... group by ...) group by ... 这样吧,有没有更高效的办法,主要数据大,并且要带有及时性,并且数据变化也很频繁,所以领导否定了事先定时统计。请问还有没有更高的效率的办法。谢谢
...全文
1268打赏收藏
求一个SQL语句,求高效的思路,在线等。
有表Dept(DeptId,DeptName.......),Emp(DeptId,EmpId,EmpName),Sell(EmpId,SellId,Money) 现在要统计出如下记录 部门名称,部门人数,销售单数,销售金额。 第一小组 5 50 50000 第二小组 7 80 120000 我想的是分组去统计,但这个应该要嵌入分组查询吧。就是select * from (select * from .... group by ...) group by ... 这样吧,有没有更高效的办法,主要
灵活运用distinct
select d.DeptName as 部门名称
,Count(distinct e.EmpID) as 部门人数
,Count(distinct s.SellId) as 销售单数
,Sum(m.Money) as 销售金额
from Dept d
left join Emp e on d.DeptID=e.DeptID
left join Sell s on e.EmpID=s.EmpID
group by d.DeptName
with total as(
select DEPT.DEPTNAME , SELL.EMPID,SELL.SELLID,SELL.MONEY,EMP.EMPNAME from sell,emp,dept
where SELL.EMPID=EMP.EMPID and EMP.DEPTID=DEPT.DEPTID
)
select a.DEPTNAME,a.人数,b.单数,c.金额 from
(select DEPTNAME,count(EMPID) as 人数 from( select distinct TOTAL.DEPTNAME,TOTAL.EMPID from total ) group by DEPTNAME)a,
(select TOTAL.DEPTNAME,sum( total.SELLID)单数 from total group by DEPTNAME)b,
(select TOTAL.DEPTNAME,sum( total.MONEY)金额 from total group by DEPTNAME)c
where a.DEPTNAME=b.DEPTNAME and a.DEPTNAME=c.DEPTNAME
order by DEPTNAME
select d.DeptName as 部门名称
,Count(e.EmpID) as 部门人数
,Count(s.SellId) as 销售单数
,Sum(m.Money) as 销售金额
from Dept d
left join Emp e on d.DeptID=e.DeptID
left join Sell s on e.EmpID=s.EmpID
group by d.DeptName