SQL从一个表中选择所有列,并在另一个表中选择另一个列的最大值

时间:2021-09-27 00:36:39

This is my first question in * and I hope I get an answer soon to my problem. :) I tried searching for quite some time from other sources but unfortunately, couldn't find a working answer.

这是我在*上的第一个问题,我希望我的问题能尽快得到答案。(收集整理我试着从其他来源找了相当长一段时间,但不幸的是,找不到有效的答案。

So, I am working on a project and since I am a newbie to sql, I cannot do this:

所以,我正在做一个项目,由于我是sql的新手,我不能这么做:

I have 2 tables:

我有两个表:

"Customers" with columns "id", "name", "last name" ("id" is primary key)
"Sessions" with columns "id", "Customer", "entrydate" ("id" is primary key)

“客户”列“id”、“名称”、“姓”(“id”是主键)“session”,列“id”、“Customer”、“entrydate”(“id”是主键)

"Customer" from "Sessions" is tied to "id" from "Customers". (foreign key)

“session”中的“Customer”与“Customers”中的“id”绑定。(外键)

I need a query that returns all columns from table "Customers" with one additional column showing the entrydate of the latest "Sessions" record, of each Customer of course. "Sessions" table may have many records for an individual "Customers" record, as you can imagine.

我需要一个查询,该查询返回表“Customers”中的所有列,以及一个附加列,其中显示每个客户的最新“session”记录的入口日期。您可以想象,“Sessions”表可能有许多针对单个“客户”记录的记录。

Thanks everybody in advance and hope to get an answer soon.

提前谢谢大家,希望能尽快得到答复。

2 个解决方案

#1


3  

I may be missing something really obvious but this sounds really really basic sql the kind you'd find in a sql tutorial https://www.w3schools.com/SQL/sql_groupby.asp

我可能遗漏了一些非常明显的东西,但这听起来确实非常基本的sql语句,您可以在sql教程https://www.w3schools.com/SQL/sql_groupby.asp中找到。

SELECT C.name,c.lastName,MAX(S.entryDate) FROM customers C
inner join Sessions S ON S.CustomerId=C.Id
group by C.name,C.lastName

#2


1  

Its as simple as that.

就这么简单。

SELECT C.id,C.name,c.lastName,MAX(S.entryDate) as lastEntry FROM customers C join Sessions S ON S.CustomerId=C.Id group by C.id

选择C.id、C.name、C. lastname、MAX(. entrydate)作为来自客户C的lastEntry。Id group by C.id

#1


3  

I may be missing something really obvious but this sounds really really basic sql the kind you'd find in a sql tutorial https://www.w3schools.com/SQL/sql_groupby.asp

我可能遗漏了一些非常明显的东西,但这听起来确实非常基本的sql语句,您可以在sql教程https://www.w3schools.com/SQL/sql_groupby.asp中找到。

SELECT C.name,c.lastName,MAX(S.entryDate) FROM customers C
inner join Sessions S ON S.CustomerId=C.Id
group by C.name,C.lastName

#2


1  

Its as simple as that.

就这么简单。

SELECT C.id,C.name,c.lastName,MAX(S.entryDate) as lastEntry FROM customers C join Sessions S ON S.CustomerId=C.Id group by C.id

选择C.id、C.name、C. lastname、MAX(. entrydate)作为来自客户C的lastEntry。Id group by C.id