我一直在爲此工作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的答案,謝謝!
我想感謝[sixlettervariables](http://stackoverflow.com/users/7116/sixlettervariables)幫助我獲得這麼大的進展 – Dean 2012-07-18 05:49:28