包含内部联接的存储过程,计数不起作用

时间:2012-11-05 19:21:27

标签: sql sql-server tsql

假设我的数据库表看起来有点像这样,包含有关某些作业的信息。

Id   | ProfessionId      | Title       | Deadline     | DateCreated | ClosingDate
1    |  5                | Something   | 01-12-2012   | 05-11-2012  | 12-11-2012
2    |  6                | Something   | 01-12-2012   | 05-11-2012  | 12-11-2012
3    |  7                | Something   | 01-12-2012   | 05-11-2012  | 12-11-2012
4    |  7                | Something   | 01-12-2012   | 05-11-2012  | 12-11-2012

我希望生成一个概述foreach职业(作业属于某个职业)并计算每个职业的任务数量。来自数据库的概述应如下所示;

Id | Name           | FriendlyUrl     | Ordinal   | NumberOfAssignments
5  | Profession 1   | profession-1    | 1         | 1
6  | Profession 2   | profession-2    | 1         | 1
7  | Profession 3   | profession-3    | 1         | 2
8  | Profession 4   | profession-4    | 1         | 0

我目前有一个存储过程返回上面的概述,除了分配数量不正确。过去有结束日期的作业(我们假设作业已结束)不应计入作业总数。

当前存储过程如下:

BEGIN
    SELECT  p.Id, 
            p.Naam, 
            p.FriendlyUrl, 
            p.Ordinal, 
            COUNT(a.ProfessionId) AS NumberOfAssignments
    FROM ME_Profession AS p 
    LEFT OUTER JOIN ME_Assignment AS a ON a.ProfessionId = p.Id
    INNER JOIN ME_Client AS c ON a.ClientId = c.Id
    INNER JOIN aspnet_Membership AS m ON m.UserId = c.UserId
    WHERE m.IsApproved = 1 
    GROUP BY p.Id, p.Naam, p.FriendlyUrl, p.Ordinal
END

我已经提出并修改了如下所示的程序,但它不起作用。感觉就像我想要太困难或遗漏一些明显的东西。可能出现什么问题?

SELECT        p.Id, p.Naam, p.FriendlyUrl, p.Ordinal, pc.NumberOfAssignments
FROM            ME_Profession AS p 
INNER JOIN ME_Assignment AS a ON a.ProfessionId = p.Id 
INNER JOIN ME_Client AS c ON a.ClientId = c.Id
INNER JOIN aspnet_Membership AS m ON m.UserId = c.UserId
INNER JOIN (SELECT a2.ProfessionId, COUNT(*) AS NumberOfAssignments FROM ME_Assignment AS a2 GROUP BY a2.ProfessionId WHERE a2.Closingdate > GETDATE()) pc ON p.ProfessionId = pc.ProfessionId
WHERE        m.IsApproved = 1 AND a.Closingdate > GETDATE()
GROUP BY p.Id, p.Naam, p.FriendlyUrl, p.Ordinal

更新1:添加了日期条件

3 个答案:

答案 0 :(得分:2)

我认为你不需要再次加入对象ME_profession,试试这个:

SELECT  p.Id, p.Naam, p.FriendlyUrl, p.Ordinal, pc.NumberOfAssignments,
        COUNT(CASE WHEN ClosingDate > GETDATE() OR ClosingDate IS NULL THEN 1 END) AS NumberOfAssignments 
FROM  ME_Profession AS p 
INNER JOIN ME_Assignment AS a 
    ON a.ProfessionId = p.Id 
INNER JOIN ME_Client AS c 
    ON a.ClientId = c.Id
INNER JOIN aspnet_Membership AS m 
    ON m.UserId = c.UserId
WHERE (m.IsApproved = 1)
GROUP BY p.Id, p.Naam, p.FriendlyUrl, p.Ordinal

答案 1 :(得分:1)

如何... LEFT OUTER JOIN(选择*来自ME_Assignment WHERE ClosingDate> GETDATE())作为......

答案 2 :(得分:0)

我没有在当前存储过程中看到满足此语句的条件:

  

过去有一个关闭日期的作业(我们假设是   任务已结束)不应该被纳入总数   分配

您可能只需要将正在进行的工作中的标准添加到现有的proc:

WHERE ClosingDate > GETDATE()