如果通过加入不在外键中,如何获得主键值?

时间:2014-05-04 07:59:45

标签: sql sql-server-2008

我跟随查询,根据需要显示结果,但我需要在结果中缺少缺少的主键值:

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

没有4月份的注册,但我需要它可用于此月或任何即将到来的月份。

不是特定于用户。提前谢谢!

1 个答案:

答案 0 :(得分: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

如果需要一些改进,请建议。