The number of SQL Statistics Department, the number of 0's departments should also be displayed

 

The same point: they are to a department table (or categories table), other tables have the department number DepartmentID (category number)

Case I: A table

 select c.DepartmentID,c.DepartmentName, t.Num AS '人员数量' from T_Department as c 
left join (select DepartmentID,COUNT(*) AS Num from T_User   group by DepartmentID) as t on c.DepartmentID= t.DepartmentID

The core idea is: Split

Table 1 The personnel department number by the number of statistics: (select DepartmentID, COUNT (*) AS Num from T_User group by CompanyID) to give t: department number, the number of department staff;

The department table with 2 t, department number in accordance with the table left connected, get: name of the department, the number of departments

 

Case II: multiple tables

Investigators statistics submitted, equipment, specifications, data source specifications table number

I was beginning to do so:

select c.CompanyName, t.Num from T_Company as c left join (select CompanyID,COUNT(*) AS Num from T_Standard as s where s.HasSubmitted=1 group by CompanyID) as t on c.CompanyID= t.CompanyID order by c.CompanyID
select c.CompanyName, t.Num from T_Company as c left join (select CompanyID,COUNT(*) AS Num from T_Investigator as s where s.HasSubmitted=1 group by CompanyID) as t on c.CompanyID= t.CompanyID order by c.CompanyID
select c.CompanyName, t.Num from T_Company as c left join (select CompanyID,COUNT(*) AS Num from T_Machine as s where s.HasSubmitted=1 group by CompanyID) as t on c.CompanyID= t.CompanyID order by c.CompanyID
select c.CompanyName, t.Num from T_Company as c left join (select CompanyID,COUNT(*) AS Num from T_DataSource as s where s.HasSubmitted=1 group by CompanyID) as t on c.CompanyID= t.CompanyID order by c.CompanyID

However, Excel and copied to a one by one.

后来我是这样的:
select c.CompanyID,c.CompanyName, t1.Num AS '调查人员数量',t2.Num AS '设备数量',t.Num AS '规范数量',t3.Num AS '数据来源规范数量' from T_Company as c
left join (select CompanyID,COUNT(*) AS Num from T_Standard as s where s.HasSubmitted=1 group by CompanyID) as t on c.CompanyID= t.CompanyID
left join (select CompanyID,COUNT(*) AS Num from T_Investigator as s where s.HasSubmitted=1 group by CompanyID) as t1 on c.CompanyID= t1.CompanyID
left join (select CompanyID,COUNT(*) AS Num from T_Machine as s where s.HasSubmitted=1 group by CompanyID) as t2 on c.CompanyID= t2.CompanyID
left join (select CompanyID,COUNT(*) AS Num from T_DataSource as s where s.HasSubmitted=1 group by CompanyID) as t3 on c.CompanyID= t3.CompanyID
order by c.CompanyID

The last assignment paste it into Excel, put forward in Excel Total:

 

Guess you like

Origin www.cnblogs.com/hao-1234-1234/p/10951418.html
Recommended