【问题标题】:SQL - Display a descriptive field based a date fieldSQL - 显示基于日期字段的描述性字段
【发布时间】:2021-05-14 16:53:19
【问题描述】:

我在 Access 中有 2 个表:

表 1 有 id、first_name 和 last_name
表2有city、date_recorded和person_id

我正在尝试运行查询以显示最早日期的名字、姓氏和城市。

我可以通过以下查询来解决这个问题,但是当我尝试将城市添加到结果中时会显示所有记录。
如何将城市添加到结果中,但每人仍然只有 1 行?

SELECT table1.first_name, table1.last_name, Min(table2.date_recorded) AS First_Occurrence
FROM table1 INNER JOIN table2 ON table1.id = table2.person_id
GROUP BY table1.first_name, table1.last_name
ORDER BY Min(table2.date_recorded);

【问题讨论】:

标签: sql ms-access


【解决方案1】:

您可以使用子查询为具有最少 date_recorded 的人选择城市,如下所示。

  select id, first_name,last_name, First_Occurrence , (select city from table2 where person_id=t.id and date_recorded=first_occurrence ) as city 
from
(
    SELECT t1.id, t1.first_name, t1.last_name, min(t2.date_recorded) AS First_Occurrence
    FROM table1 as t1 INNER JOIN table2 as t2 ON t1.id = t2.person_id
    GROUP BY  t1.id,t1.first_name, t1.last_name
    order by min(t2.date_recorded) 
) t

【讨论】:

  • 对不起,我错过了一个逗号。请立即尝试。
  • 您是否在 Access 中构建了用于测试查询的表?我做到了。你应该得到同样的错误。
  • 不。现在明白了。非常感谢
  • @June7 我已经修改了答案。
猜你喜欢
  • 2014-02-23
  • 2016-07-08
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 1970-01-01
  • 2021-10-07
相关资源
最近更新 更多