如何使用MAX选择distinct并返回全表字段

时间:2015-03-06 00:51:07

标签: sql ms-access

我的表:

id  name    empid   t_date              lesson          score
1   Allen   9527    2015-02-11 15-47-56 fire            100
2   Allen   9527    2015-02-11 15-49-44 back            100
4   Allen   9527    2015-02-11 15-51-22 machine_guard   100
6   Allen   9527    2015-02-11 15-52-28 machine_guard   25
8   Allen   9527    2015-02-11 15-53-23 lockout         100
9   Allen   9527    2015-02-11 15-54-01 fire            36
10  Jeremy  9845    2015-02-12 11-08-43 back            92
11  Jeremy  9845    2015-02-12 14-06-50 back            36
12  Jeremy  9845    2015-02-12 14-25-06 machine_guard   90
13  Jeremy  9845    2015-02-12 14-43-32 machine_guard   95

我需要区分名称和课程,并且还需要得分的最大值。

我想要的结果:

id  name    empid   t_date              lesson          score
1   Allen   9527    2015-02-11 15-47-56 fire            100
2   Allen   9527    2015-02-11 15-49-44 back            100
4   Allen   9527    2015-02-11 15-51-22 machine_guard   100
8   Allen   9527    2015-02-11 15-53-23 lockout         100
10  Jeremy  9845    2015-02-12 11-08-43 back            92
13  Jeremy  9845    2015-02-12 14-43-32 machine_guard   95

我试过了: SQL:

SELECT distinct name,lesson,max(score) as scores from test
where t_date between '2015-02-11' and '2015-02-13'
group by name,lesson

name    lesson          scores
Allen   back            100
Allen   fire            100
Allen   lockout         100
Allen   machine_guard   100
Jeremy  back            92
Jeremy  machine_guard   95

我不知道如何将t_date ..字段添加到结果中。表格的完整字段。如果有相同的分数,同名和课程,我想选择早期的t_date之一。

1 个答案:

答案 0 :(得分:1)

您还可以按照我在预期结果中观察到的MIN() t_date获得name lesson来获取SELECT DISTINCT name, lesson, MAX(score) AS scores, MIN(t_date) AS t_date FROM test WHERE t_date BETWEEN '2015-02-11' AND '2015-02-13' GROUP BY name,lesson 每个SELECT MIN(id) AS id, name, empid, MIN(t_date) AS t_date, lesson, MAX(score) AS score FROM test WHERE t_date BETWEEN '2015-02-11' AND '2015-02-13' GROUP BY name,empid,lesson 组的早期日期看见如下:

{{1}}

您可以使用以下查询来获得所需的结果:

{{1}}