2012-07-18 75 views
4

我一直在爲此工作2天,但無法弄清楚。我希望比我聰明的人會放棄這一點。Linq To Sql或SQL中的困難查詢

比方說,我有如下表:

Rating: 
    Id | Name 
    1 | A 
    2 | B 
    3 | C 
    4 | D 
    5 | E 

Inspection: 
    Id | Date (mm/dd/yyyy) 
    1 | 01/04/2012 
    2 | 04/04/2012 
    3 | 28/03/2012 
    4 | 04/04/2012 

Observation: 
    Id | InspectionId | RatingId 
    1 | 2   | 3 
    2 | 1   | 2 
    3 | 4   | 3 
    4 | 2   | 1 
    5 | 3   | 3 
    6 | 1   | 2 

我想查詢返回:

RatingName | Date(mm/dd/yyyy) | ObservationCount 
A   | 01/04/2012  | 0 
B   | 01/04/2012  | 1 
C   | 01/04/2012  | 1 
D   | 01/04/2012  | 0 
E   | 01/04/2012  | 0 
A   | 04/04/2012  | 1 
B   | 04/04/2012  | 0 
C   | 04/04/2012  | 2 
D   | 04/04/2012  | 0 
E   | 04/04/2012  | 0 
A   | 28/03/2012  | 0 
B   | 28/03/2012  | 0 
C   | 28/03/2012  | 1 
D   | 28/03/2012  | 0 
E   | 28/03/2012  | 0 

所以我需要觀測的數量每個等級每個日期。是的,我需要有返回0觀察記錄,因爲我在堆疊圖表中使用這些數據,沒有它們會引發錯誤。我已經設法得到上面的表,但沒有返回0觀察與下面的Linq To Sql查詢的記錄,但從這一點我卡住了。

MyDataContext DB = new MyDataContext(); 

var data = 
    (from r in DB.Ratings 
    join o in DB.Observations on r.Id equals o.RatingId into ro 

    from observation in ro.DefaultIfEmpty() 
    join i in DB.Inspections on observation.InspectionId equals i.Id into roi 

    from q in roi.DefaultIfEmpty() 
    group q by new { Name = r.Name, Date = q.Date } into grouped 
    select 
    new 
    { 
     RatingName = grouped.Key.Name, 
     Date = grouped.Key.Date, 
     ObservationCount = grouped.Count(x => x != null) 
    }).OrderBy(x => x.Date); 

我將不勝感激Linq To Sql或普通的舊SQL的答案,謝謝!

+0

我想感謝[sixlettervariables](http://stackoverflow.com/users/7116/sixlettervariables)幫助我獲得這麼大的進展 – Dean 2012-07-18 05:49:28

回答

4

您應該在兩個參考表上嘗試一個CROSS JOIN,然後OUTER JOIN回到您的'數據'表 - 然後檢查Observation是否爲空...然後分組和總和!

SELECT 
    [Name], 
    [Date], 
    SUM([Exists]) 
FROM 
(
SELECT 
    name, 
    [Date], 
    CASE WHEN o.Id IS NULL THEN 0 
     ELSE 1 
    END as [Exists] 
FROM 
    Rating r CROSS JOIN 
    Inspection i 
    LEFT OUTER JOIN Observation o 
     ON o.RatingId = r.Id AND o.InspectionId = i.Id 
) as [source] 
GROUP BY [Name], [Date] 
ORDER BY 
    [Date], 
    name 

翻譯到LINQ將是類似的兩個步驟的過程 - 獲得所述內的結果集(檢查觀察是否是NULL),分組和求和之前。

+1

我:2天仍在工作。你:17分鐘。謝謝! – Dean 2012-07-18 06:13:49

+0

有時你只需要一雙新的眼睛:) – 2012-07-19 23:29:48