我有以下表结构也提到我的预期输出请帮我查询,因为我对SQL查询不太了解
表1:类别
Name CatId
A 1
B 2
C 3
表2:Emp详细信息
FName Id Dob CatId
Pratik 1 1958-04-06 2
Praveen 3 1972-05-12 1
Nilesh 2 1990-12-12 2
到目前为止,我试图通过以下方式获得所有结果:
SELECT A.Code,A.EmpName,A.DOB,B.cname
FROM EMPMASTER A
JOIN CATMASTER B ON A.cCode = B.ccode AND A.Compcode = B.CompCode
WHERE A.compcode = 'C0001' AND month(A.DOB) >= 1
AND MONTH(A.DOB) <= 12 AND A.termflag='L'
ORDER BY A.DOB
但我的问题是,我还希望显示摘要结果
预期汇总输出:
Grouping No Of Employees
A 1
B 2
C 0
答案 0 :(得分:8)
我认为您可以使用LEFT JOIN
,GROUP BY
和COUNT
,如下所示:
SELECT [Grouping] = c.Name,
[No Of Employees] = COUNT(e.ID)
FROM Category AS c
LEFT JOIN EmpDetails AS e
ON e.CatId = c.CatId
GROUP BY c.Name;
答案 1 :(得分:1)
尝试这个:
SELECT A.NAME,
(SELECT COUNT(*) FROM #EMP B WHERE A.CATID = B.CATID) AS COUNT
FROM #TEMP A