1

我有两个这样的表:

    Table1
    ________
StudentNumbers  ExamType
1234        1
2343        2   
3345        5
3454        1
5465        2
...
    Table2
    ________
StudentNumbers  ExamType      ExamDate  School  Area
1234        1       0825    warren  ny
1234        1       0829    north   nj  
1233        2       0921    north   nj              
2343        1       0922    warren  ny
2343          1                  0925     north   ny
...

我需要通过使用 Table1 中特定 ExamType 的数据从 Table2 中找出每个学生的最大 ExamDate。到目前为止我已经想出了这个,但这似乎不正确:

Select t2.StudentNumbers, t2.ExamType, max(t2.ExamDate), t2.School, t2.Area 
from Table2 as t2
Join Table1 as t1 on
t1.StudentNumbers = t2.StudentNumbers 
where t2.ExamType = 1

我在选择列表中收到错误,因为它不包含在聚合函数或 group by 子句中

它基本上应该返回:

StudentNumbers  ExamType      ExamDate  School  Area
  1234      1       0829    north   nj  
  2343          1                  0925     north   ny
4

3 回答 3

1

使用max()或其他聚合函数时,需要对结果集中的其他字段进行分组。

Select t2.StudentNumbers, t2.ExamType, max(t2.ExamDate), t2.School, t2.Area 
from Table2 as t2
Join Table1 as t1 on
t1.StudentNumbers = t2.StudentNumbers 
where t2.ExamType = 1
group by t2.StudentNumbers, t2.ExamType, t2.School, t2.Area

这将为您提供每位学生、考试类型、学校和地区的最新考试日期。

于 2013-08-26T21:31:14.380 回答
0

您需要使用GROUP BY或将聚合更改为窗口函数(例如MAX(t2.ExamDate) over (partition by t2.StudentNumbers, t2.ExamType)

顺便说一句,正如一些评论中提到的,考虑到第一个表中的数据包含在第二个表中,整个想法JOIN并没有真正有用。

于 2013-08-26T21:34:33.143 回答
0

错误告诉你到底出了什么问题

  1. xxx在选择列表中无效,即选择列有问题xxx
  2. 因为它不包含在任何一个中
    • 聚合函数,例如MAX, SUM,COUNT
    • group by 子句,例如GROUP BY xxx

因此,您要么必须在聚合函数中使用该列,要么将该列放在GROUP BY子句中。

鉴于您只需要“ExamDate从”中找到每个学生的最大值,Table2并且ExamType已经在Table2您选择的许多列中,并且连接似乎是不必要的,并且可以将查询简化为

SELECT t2.StudentNumbers
    , MAX(t2.ExamDate) AS MaxExamDate
FROM Table2 AS t2
WHERE t2.ExamType = 1
GROUP BY t2.StudentNumbers
于 2013-08-26T21:41:02.770 回答