4

我已经为此工作了 2 天,但我无法弄清楚。我希望比我聪明的人会尝试一下。

假设我有以下表格:

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 Observations 的记录,因为我在堆叠图表中使用这些数据,没有它们会引发错误。我已经设法获得了上表,但没有使用以下 Linq To Sql 查询返回 0 Observations 的记录,但从这一点开始我就卡住了。

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 的答案,谢谢!

4

1 回答 1

4

您应该CROSS JOIN在两个参考表上尝试 a,然后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)。

于 2012-07-18T05:55:27.997 回答