需要解决方案以下的Sql查询

时间:2017-02-14 17:50:00

标签: sql sql-server

select 
    n_CompanyId,
    n_CompanyCode,
    s_CompanyName,
    (select COUNT(em.n_CompanyId) as Total_Employee
     from tbl_CompanyMaster cm
     inner join tbl_EmployeeMaster em on (cm.n_CompanyId = em.n_CompanyId)
     group by cm.n_CompanyId),
    (select COUNT(bm.n_CompanyId) as Total_Branch
     from tbl_CompanyMaster cm
     inner join tbl_BranchMaster bm on (cm.n_CompanyId = bm.n_CompanyId)
     group by cm.n_CompanyId),
    (select COUNT(ca.n_CompanyId) as Total_Employee
     from tbl_CompanyMaster cm
     inner join tbl_CompanyApplicationRigths ca on (cm.n_CompanyId = ca.n_CompanyId)
     group by cm.n_CompanyId),
    d_InsertDate,
    d_ModifiyDate
from 
    tbl_CompanyMaster
group by 
    n_CompanyId
order by 
    n_CompanyId asc

当我尝试这样的消息时,如

  

专栏' tbl_CompanyMaster.n_CompanyCode'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

当我把它拿来时

select 
    n_CompanyId,
    (select COUNT(em.n_CompanyId) as Total_Employee
     from tbl_CompanyMaster cm
     inner join tbl_EmployeeMaster em on (cm.n_CompanyId = em.n_CompanyId)
     group by cm.n_CompanyId),
    (select COUNT(bm.n_CompanyId) as Total_Branch
     from tbl_CompanyMaster cm
     inner join tbl_BranchMaster bm on (cm.n_CompanyId = bm.n_CompanyId)
     group by cm.n_CompanyId),
    (select COUNT(ca.n_CompanyId) as Total_Employee
     from tbl_CompanyMaster cm
     inner join tbl_CompanyApplicationRigths ca on (cm.n_CompanyId = ca.n_CompanyId)
     group by cm.n_CompanyId)
from 
    tbl_CompanyMaster
group by 
    n_CompanyId
order by 
    n_CompanyId asc

我收到错误:

  

子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

CompanyApplicationRigths是一个错字吗?它应该是CompanyApplicationRights吗?

select 
   n_CompanyId
 , Total_Employee = (
  select count(em.n_CompanyId) 
  from tbl_EmployeeMaster em 
  where cm.n_CompanyId = em.n_CompanyId
    )
 , Total_Branch = (
  select count(bm.n_CompanyId) 
  from tbl_BranchMaster bm 
  where cm.n_CompanyId = bm.n_CompanyId
  )
 , Total_ApplicationRigths = (
  select count(ca.n_CompanyId)
  from tbl_CompanyApplicationRigths ca 
  where  cm.n_CompanyId = ca.n_CompanyId)
  )
from tbl_CompanyMaster as cm
group by n_CompanyId
order by n_CompanyId asc

也可以写成:

select
    n_CompanyId
  , Total_Employee = count(em.*)
  , Total_Branch =  count(bm.*)
  , Total_ApplicationRigths = count(ca.*)
from tbl_CompanyMaster as cm
  left join tbl_EmployeeMaster em 
    on cm.n_CompanyId = em.n_CompanyId
  left join tbl_BranchMaster bm 
    on cm.n_CompanyId = bm.n_CompanyId
  left join tbl_CompanyApplicationRigths ca 
    on cm.n_CompanyId = ca.n_CompanyId
group by n_CompanyId
order by n_CompanyId asc