2014-06-21 52 views
0

首先,我很抱歉我被選爲這個問題的壞頭銜。 :)如何選擇常數值,如果沒有找到考慮值?

在我的數據庫,我有員工評論表,因爲你如下圖所示。每個員工可以保存他/她的活動評論表和經理可以看到員工活動的報告。

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

RIGHT帶有日曆表時,本質上12個整數。 – Mihai

+0

我如何在** EntityFramework **中做到這一點? –

回答

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; 
+0

我該如何用** linq **查詢來做到這一點?可能嗎? –

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); 
     } 
相關問題