如何加入两个sql语句

时间:2013-11-25 17:47:51

标签: sql sql-server join

我有两个查询返回正确的结果。其中之一是:

select distinct epr.DepartmentCode 
from [dbo].[EmployeePayRates] epr 
join [dbo].[EmployeeTimecards] et on epr.EmployeeID = et.EmployeeID 
where StoreID = 89

它检查在商店89中签入的所有不同部门员工。查询返回:

DepartmentCode
1
2
5

第二个查询是:

SELECT DISTINCT 
    DepartmentCode, count(DISTINCT EmployeeID) 
FROM [dbo].[EmployeeTimecards] 
WHERE EmployeeTimecardDate = '2013-11-25' 
  AND StoreID = 89 
GROUP BY 
   DepartmentCode

它返回商店89中每个部门的员工人数。表格如下:

DepartmentCode          EmployeeCount
1                       17
5                       7

我试图让它看起来像:

DepartmentCode          EmployeeCount
1                       17
2                       0
5                       7

如果有人会告诉我如何加入这些查询,我将非常感激。 提前谢谢。

2 个答案:

答案 0 :(得分:3)

您可以将第一个查询移动到子查询中,然后将LEFT JOIN移回到您的表中,并执行相同的计数:

WITH DepartmentCodes AS
(   SELECT  DISTINCT epr.DepartmentCode 
    FROM    [dbo].[EmployeePayRates] epr 
            JOIN [dbo].[EmployeeTimecards] et 
                ON epr.EmployeeID = et.EmployeeID 
    WHERE   StoreID = 89
)
SELECT  dc.DepartmentCode,
        EmployeeCount = COUNT(DISTINCT c.EmployeeID)
FROM    DepartmentCodes dc
        LEFT JOIN [dbo].[EmployeeTimecards]  c
            ON dc.DepartmentCode = c.DepartmentCode
            AND EmployeeTimecardDate = '20131125' 
            AND StoreID = 89 
GROUP BY dc.DepartmentCode;

另外,我将字符串文字日期更改为文化不变格式yyyyMMdd,因为即使ISO标准yyyy-MM-dd在某些地区也可能被误解为yyyy-dd-MM。虽然不是文章的主要内容Aaron Bertrand在他的文章mis-handling date / range queries

中涵盖了这种格式问题

答案 1 :(得分:0)

我选择使用Common Table表达式来连接两个查询。在我的博客上查看我的CTE文章 - http://craftydba.com/?p=1234

--
-- Join cteDeptCode 2 cteEmpPerDept
--
;
with cteDeptCode (DeptCode) as
(
select distinct epr.DepartmentCode 
from [dbo].[EmployeePayRates] epr 
join [dbo].[EmployeeTimecards] et 
on epr.EmployeeID = et.EmployeeID 
where StoreID = 89
),
cteEmpPerDept(DeptCode, EmpCnt) as
(
SELECT DISTINCT 
DepartmentCode, count(DISTINCT EmployeeID) 
FROM [dbo].[EmployeeTimecards] 
WHERE 
EmployeeTimecardDate = '2013-11-25' AND StoreID = 89 
GROUP BY DepartmentCode
)
select d.DeptCode, a.EmpCnt 
from cteDeptCode d 
left join cteEmpPerDept e 
on d.DeptCode = e.DeptCode