数据:
Name | Score | Date
==
John | 10 | 09/01/2012
John | 20 | 09/01/2012
John | 5 | 09/01/2012
Frank | 20 | 11/01/2012
我想运行一个SQL语句,它只会从每天只获得最高分,所以我不希望从一个日期得到三个分数,只有最高分。所以从SQL中我想要的回报是:
John | 20 | 09/01/2012
Frank | 20 | 11/01/2012
是否可以通过SQL执行此操作,目前我可以通过检查日期来提取所有内容。但如果可以直接从数据库中进行,那将会很棒。
我尝试了一些解决方案,但因为日期和分数并不明显,因为我想要最高,我不确定从哪里开始。 SQL正与MS Access数据库一起使用。
答案 0 :(得分:3)
这是一个完整的例子。我是在Oracle中完成的,所以你可能需要为Access调整一些语法。
CREATE TABLE tbl1 (NAME VARCHAR2(100), score INT, Dt DATE);
INSERT INTO tbl1 VALUES ('John',10,to_date('20120901','YYYYMMDD'));
INSERT INTO tbl1 VALUES ('John',20,to_date('20120901','YYYYMMDD'));
INSERT INTO tbl1 VALUES ('John',5,to_date('20120901','YYYYMMDD'));
INSERT INTO tbl1 VALUES ('Harry',15,to_date('20120901','YYYYMMDD'));
INSERT INTO tbl1 VALUES ('Frank',20,to_date('20121101','YYYYMMDD'));
select a.dt
, b.name
, a.score
FROM (SELECT dt
, MAX(score) score
FROM tbl1
GROUP BY dt) a
, (SELECT NAME
, dt
, MAX(score) score
FROM tbl1
GROUP BY name, dt) b
WHERE a.dt = b.dt
AND a.score = b.score
<强>输出:强>
1 11/1/2012 Frank 20
2 9/1/2012 John 20
请注意,如果两个人在给定的一天获得最高分,则会同时打印两者。例如:
INSERT INTO tbl1 VALUES ('John',10,to_date('20120901','YYYYMMDD'));
INSERT INTO tbl1 VALUES ('John',20,to_date('20120901','YYYYMMDD'));
INSERT INTO tbl1 VALUES ('John',5,to_date('20120901','YYYYMMDD'));
INSERT INTO tbl1 VALUES ('Harry',20,to_date('20120901','YYYYMMDD'));
INSERT INTO tbl1 VALUES ('Frank',20,to_date('20121101','YYYYMMDD'));
select a.dt
, b.name
, a.score
FROM (SELECT dt
, MAX(score) score
FROM tbl1
GROUP BY dt) a
, (SELECT NAME
, dt
, MAX(score) score
FROM tbl1
GROUP BY name, dt) b
WHERE a.dt = b.dt
AND a.score = b.score
<强>输出:强>
DT NAME SCORE
1 11/1/2012 Frank 20
2 9/1/2012 John 20
3 9/1/2012 Harry 20
答案 1 :(得分:2)
我想这很简单
Select [Name], max([score]) as Score, [Date] from scoresTable
group by [Date], [Name]
更准确但有点复杂
select o.[Name], i.[Date], i.Score from scoresTable o
inner join (select [Date], max(Score) as Score
from scoresTable group by [Date]) as i
on o.[Date] = i.[Date] and i.Score = o.Score
更多,如果您的日期字段也包含时间
select o.[Name], i.[Date], i.Score from scoresTable o
inner join (select convert(varchar, [Date], 101) as Date, max(Score) as Score
from scoresTable
group by convert(varchar, [Date], 101)) as i
on convert(varchar, o.[Date], 101) = i.[Date] and i.Score = o.Score