2

数据:

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 数据库一起使用。

4

2 回答 2

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
于 2012-04-19T14:18:53.347 回答
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
于 2012-04-19T14:19:20.657 回答