简体   繁体   中英

SQL Select all columns from one table and Max value of another column on another table

This is my first question in stackoverflow 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:

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)

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

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.

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

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

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

就这么简单。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM