2014-05-04 76 views
0

我下面的查詢時顯示爲所需要的結果,但我需要得到缺少的主鍵值失蹤結果:如何獲得主鍵值,如果不通過連接出現在外鍵中?

SELECT 
    tbl1.SignedByUserID, tbl2.FullName, 
    COUNT(tbl1.OutletID) AS TotalSignups, 
    DATENAME(Month, tbl1.SignupDate) AS Month 
FROM  
    dbo.tblMer_Outlet AS tbl1 
LEFT OUTER JOIN 
    dbo.tblGen_Users AS tbl2 ON tbl1.SignedByUserID = tbl2.UserID 
WHERE 
    (tbl1.SignupDate >= '2014-04-01 00:00:00' 
    AND tbl1.SignupDate <= '2014-04-30 23:59:59') 
GROUP BY 
    tbl1.SignedByUserID, tbl2.FullName, DATENAME(Month, tbl1.SignupDate) 
ORDER BY 
    tbl2.FullName 

該查詢返回以下結果:

SignedByUserID  FullName  TotalSignups  Month 
-------------------------------------------------------- 
9     Babu Raj  16    April 
11     Faheem   19    April 
39     Fasil Abbas 16    April 
29     Hafiz Suleman 10    April 
12     Hussain Abbas 16    April 
15     Khawaja Aashan 33    April 
33     M. Danyal  16    April 
41     M. Qasim  01    April 
32     M. Yousuf  16    April 
37     Noman Yousaf 14    April 
40     Sajid Saleem 16    April 
5     Sales   10    April 
20     Tauseef Anees 23    April 
35     Umar Akbar  11    April 
22     Willie   09    April 

但我的用戶表中包含1個更多的價值:

38     Bilal Mateen 

不具有對四月份的一個註冊,但我需要它availabl e爲此或任何即將到來的月份。

不是特定於用戶。提前致謝!

+0

Mysql或sql-server? –

+0

SQL Server 2008/2012 – eligiable

回答

0

終於得到它固定...

SELECT A.UserID, A.FullName, ISNULL(B.TotalSignups,0) AS TotalSignups, B.Month FROM 
(
SELECT UserID, FullName 
FROM tblGen_Users 
WHERE GroupID = 4 
) AS A LEFT OUTER JOIN 
(
SELECT SignedByUserID, COUNT(1) AS TotalSignups, DATENAME(Month, SignupDate) AS Month 
FROM tblMer_Outlet 
WHERE SignupDate BETWEEN '2014-04-01' AND '2014-05-01' 
GROUP BY SignedByUserID, DATENAME(Month, SignupDate) 
) AS B ON A.UserID = B.SignedByUserID 
ORDER BY A.FullName 

如果需要一些改進,請建議。