合并两个查询以获取两列中的数据

Combine two queries to get the data in two columns

SELECT 
    tblEmployeeMaster.TeamName, SUM(tblData.Quantity) AS 'TotalQuantity'
FROM 
    tblData 
INNER JOIN
    tblEmployeeMaster ON tblData.EntryByHQCode = tblEmployeeMaster.E_HQCode 
INNER JOIN
    tblPhotos ON tblEmployeeMaster.TeamNo = tblPhotos.TeamNo
WHERE
    IsPSR = 'Y'
GROUP BY 
    tblPhotos.TeamSort, tblPhotos.TeamNo, tblPhotos.Data, 
    tblEmployeeMaster.TeamName
ORDER BY
    tblPhotos.TeamSort DESC, TotalQuantity DESC

这个returns

使用这个语句

select TeamName, count(TeamName) AS 'Head Count' 
from dbo.tblEmployeeMaster
where IsPSR = 'Y'
group by teamname

哪个returns

我想将这 2 个查询合并为 1 个以获得以下结果。

尝试联合/联合但没有成功:(

任何帮助都会非常有帮助。

您可以简单地使用子查询如下:

SELECT tblEmployeeMaster.TeamName, SUM(tblData.Quantity) AS 'TotalQuantity', 
        MAX(HEAD_COUNT) AS HEAD_COUNT, -- USE THIS VALUE FROM SUB-QUERY
        CASE WHEN MAX(HEAD_COUNT) <> 0 
             THEN SUM(tblData.Quantity)/MAX(HEAD_COUNT) 
        END AS PER_MAN_CONTRIBUTION -- column asked in comment
  FROM tblData INNER JOIN
  tblEmployeeMaster ON tblData.EntryByHQCode = tblEmployeeMaster.E_HQCode INNER JOIN
  tblPhotos ON tblEmployeeMaster.TeamNo = tblPhotos.TeamNo
  -- FOLLOWING SUB-QUERY CAN BE USED
  LEFT JOIN (select TeamName, count(TeamName) AS HEAD_COUNT 
                from dbo.tblEmployeeMaster
               where IsPSR = 'Y' group by teamname) AS HC  
         ON HC.TeamName = tblEmployeeMaster.TeamName
  where IsPSR = 'Y'
  GROUP BY tblPhotos.TeamSort, tblPhotos.TeamNo, tblPhotos.Data,tblEmployeeMaster.TeamName
  order by tblPhotos.TeamSort desc, TotalQuantity desc