2013-11-25 94 views
2

我有兩個查詢返回正確的結果。其中之一是:如何加入兩條sql語句

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 

我會很感激,如果有人會告訴我如何加入這些查詢。 在此先感謝。

回答

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

+0

我認爲這將不起作用,因爲以您的'DepartmentCodes'開始,CTE排除僱員結果沒有任何員工卡關聯的結果。也許你甚至不需要CTE? – Sebas

+0

@Sebas爲什麼不呢? CTE中的查詢與返回所需3個部門代碼的問題中的第一個查詢完全相同,而我僅將'LEFT JOIN'返回到'EmployeeTimecards',因此沒有理由不包含所有3行在最後的結果。然而,你是對的,CTE不是必需的,在我的更新中,我給出了只有一個連接的解決方案。 – GarethD

+0

@GarethD第二個輸出錯誤的數據。但第一個作爲魅力!謝謝! –

0

我選擇使用公用表表達式來加入這兩個查詢。查看我的博客上的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