如果找不到Considered值,如何选择常量值?

时间:2014-06-21 08:55:27

标签: sql sql-server entity-framework group-by

首先,我很抱歉我选择了这个问题。 :)

在我的数据库中,我有员工评论表,如下所示。每位员工都可以将他/她的活动保存在评论表中,经理可以查看员工活动报告。

enter image description here

我使用此查询选择特定中每个月的员工活动。

SELECT  Month ,
    ISNULL(( SELECT ( FirstName + '' + LastName )
             FROM   dbo.Employee
             WHERE  EmployeeID = C.EmployeeID
           ), '') [Name] ,
    ISNULL(COUNT(EmployeeID), 0) [Count]
FROM    dbo.Comment AS C
WHERE Year = 1393
GROUP BY Month ,
        EmployeeID
ORDER BY C.EmployeeID

结果是:

enter image description here

但我想这样做,如果每个员工在每个月都没有任何活动,那么选择该月的Month|Name|0行和员工。

我该怎么做?

更新 我已将查询更改为:

DECLARE @aa TABLE ( m INT )

DECLARE @c INT= 1

WHILE @c < 13
    BEGIN
        INSERT  INTO @aa
                ( m )
        VALUES  ( @c  -- m - int
                  )
        SET @c = @c + 1

    END

SELECT  m ,
        ( SELECT    ( FirstName + ' ' + LastName )
          FROM      dbo.Employee
          WHERE     EmployeeID = C.EmployeeID
        ) [Name] ,
        COUNT(CommentID) [Count]
FROM    dbo.Comment AS C
        RIGHT JOIN @aa ON m = Month
GROUP BY m ,
        EmployeeID
ORDER BY m

然后结果是:

enter image description here

但我希望得到这样的结果:

enter image description here

2 个答案:

答案 0 :(得分:1)

下面是一种方法,使用CTE和CROSS JOIN来获取所有员工/月份组合。

WITH
    employees AS (
        SELECT 
            EmployeeID
            , FirstName + '' + LastName AS Name
        FROM   dbo.Employee
    )
    ,months AS (
        SELECT month FROM (VALUES(1),(2),(3),(4),(5),(6),(7),(8),(8),(10),(11),(12)) AS months(Month)
    )
SELECT
     m.Month
    ,e.Name
    ,(SELECT COUNT(*) 
        FROM dbo.Comment AS c 
        WHERE 
            c.EmployeeID = e.EmployeeID 
            AND c.Month = m.Month
            AND c.Year = 1393
    ) AS Count
FROM months AS m
CROSS JOIN employees AS e
ORDER BY
     Month
    ,Name;

答案 1 :(得分:1)

您需要创建一个名为Months的表,并在其中插入1到12的数据。然后在entityframework中,您可以创建以下查询以从注释,员工和月份表中获取数据:

var q = from m  in stackExchangeExampleEntities.Months
                from e in stackExchangeExampleEntities.Employees
            select new
            {
                EmployeeName = e.FirstName,
                Month = m.Id,
                Count = (from c in stackExchangeExampleEntities.Comments
                        where c.EmployeeId ==e.EmployeeId && c.Month == m.Id && c.Year == 1393
                        select c).Count()


            };
        foreach (var data in q)
        {
            Console.WriteLine(data.Month + "," + data.EmployeeName +"," + data.Count);
        }