0

我有这个查询:

SELECT TOP 1 A.ExamTemplateId, A.Id AS AnsweredTestId, AVG(B.Score) AS AvgScore, A.[Date]
FROM AnsweredTest AS A
INNER JOIN AnsweredWorksheet AS B ON (A.Id = B.AnsweredTestId)
WHERE A.StudentId = 'OPA-3DKCL2' AND A.ExamTemplateId = 1
GROUP BY A.Id, A.ExamTemplateId, A.[Date]
ORDER BY AvgScore DESC

请检查我是否有WHERE收到静态号码的条件。查询结果为:

例 1

例 2 在此处输入图像描述

这是正确的!但现在,我想显示 ExamTemplate 表中的所有记录。但现在我不知道我该如何做到这一点。我正在考虑创建一个功能,但我不确定,这只是一个想法。

我想收到的最终输出是最后记录的并集:

1   1   0.7 2012-10-21 19:50:11.697
2   10  0.555555555555556   2012-10-22 18:58:24.163

提前致谢。

更新:

我用黄色突出显示了我感兴趣的行。我在最后一个查询中设置,TOP 1因为我想获得最高平均分ExamTemplateId。这就是全部。

在此处输入图像描述

4

3 回答 3

3

听起来您想A.ExamTemplateId = 1用值列表替换 。如果是这样,那么您应该能够使用类似于以下内容的内容:

SELECT A.ExamTemplateId, 
  A.Id AS AnsweredTestId, 
  AVG(B.Score) AS AvgScore, 
  A.[Date]
FROM AnsweredTest AS A
INNER JOIN AnsweredWorksheet AS B 
  ON (A.Id = B.AnsweredTestId)
WHERE A.StudentId = 'OPA-3DKCL2' 
  AND A.ExamTemplateId IN (SELECT ExamTemplateId -- use a SELECT statement to get all template id
                           FROM ExamTemplateTable)
GROUP BY A.Id, A.ExamTemplateId, A.[Date]
ORDER BY AvgScore DESC

如果你只想要一个值,那么你可以使用这样的东西:

select ExamTemplateId,
    AnsweredTestId,
    AvgScore,
    [Date]
from 
(
  select ExamTemplateId,
    AnsweredTestId,
    AvgScore,
    [Date],
    row_number() over(partition by ExamTemplateId order by AvgScore) rn
  from
  (
    SELECT A.ExamTemplateId, 
      A.Id AS AnsweredTestId, 
      AVG(B.Score) AS AvgScore, 
      A.[Date]
    FROM AnsweredTest AS A
    INNER JOIN AnsweredWorksheet AS B 
      ON (A.Id = B.AnsweredTestId)
    WHERE A.StudentId = 'OPA-3DKCL2' 
      AND A.ExamTemplateId IN (SELECT ExamTemplateId -- use a SELECT statement to get all template id
                               FROM ExamTemplateTable)
    GROUP BY A.Id, A.ExamTemplateId, A.[Date]
  ) sc
) mx
where rn = 1
于 2012-10-26T18:54:36.720 回答
1

使用分区依据。

With t AS (
    SELECT A.ExamTemplateId, A.Id AS AnsweredTestId, AVG(B.Score) AS AvgScore, A.[Date] 
    FROM AnsweredTest AS A
    INNER JOIN AnsweredWorksheet AS B ON (A.Id = B.AnsweredTestId)
    WHERE A.StudentId = 'OPA-3DKCL2' --AND A.ExamTemplateId in (...)
    GROUP BY A.Id, A.ExamTemplateId, A.[Date]
)
, w AS (
    SELECT *, 
        ROW_NUMBER() OVER (PARTITION BY ExamTemplateId ORDER BY AvgScore DESC) rank
    FROM t 
)
SELECT * FROM w 
WHERE rank = 1
于 2012-10-26T19:54:10.300 回答
0

At first I thought you were looking to see all students, but I guess you want over all exam templates - any reason you can't just remove the top 1 filter and take the exam template out of the where? The averages would be computed per-exam template which is I think what you want.

SELECT A.ExamTemplateId, A.Id AS AnsweredTestId, AVG(B.Score) AS AvgScore, A.[Date]
FROM AnsweredTest AS A
INNER JOIN AnsweredWorksheet AS B ON (A.Id = B.AnsweredTestId)
WHERE A.StudentId = 'OPA-3DKCL2' 
GROUP BY A.Id, A.ExamTemplateId, A.[Date]
ORDER BY AvgScore DESC`
于 2012-10-26T18:58:04.390 回答