SQL:按原因分组

时间:2017-02-15 08:46:30

标签: sql ms-access

我有一个如下所示的Access表:

ID      Country       Application Date
--------------------------------
12      France        12/01/2016
12      Germany       01/01/2017
13      Germany       01/02/2017
14      Spain         23/01/2017
14      Germany       01/02/2017
15      
16      Greece        01/01/2017

我希望每个ID都有一个最近的申请日期。

我试过了:

SELECT ID, Country, Max(Application Date)
FROM MyTable
GROUP BY ID

但是Access拒绝了这个查询,并希望我在group by子句中添加国家/地区,然后才能工作。 此外,我希望能够获取没有国家和申请日期的行(比如ID = 15的行)。

预期结果将是:

ID      Country       Application Date
--------------------------------
12      Germany       01/01/2017
13      Germany       01/02/2017
14      Germany       01/02/2017
15      
16      Greece        01/01/2017

2 个答案:

答案 0 :(得分:3)

我认为这是你想要的

select t1.* from MyTable as t1 inner join
(
SELECT ID, Max(Application Date) as Application Date
FROM MyTable
GROUP BY ID
) as t2 on t1.Id=t2.ID and t1.Application Date=t2.Application Date

答案 1 :(得分:0)

它适用于您的输入数据并返回正确的输出数据。试试吧,请)

SELECT d.id, MyTable.country, d.datemax
FROM (SELECT ID as id, Max(AppDate) as datemax
FROM MyTable
GROUP BY ID) as d 
,MyTable
WHERE d.id = MyTable.id and datemax = MyTable.appdate
OR (datemax is null and country is null)