SQL Select all columns from one table and max value of another column in another table

This is my first question on stackoverflow and I hope I get an answer to my problem soon. :) I tried to find quite a while from other sources but unfortunately I couldn't find a working answer.

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

I have 2 tables:

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

The "Client" from the "Session" is tied to the "id" from the "Clients". (external key)

I need a query that returns all columns from the Customers table with another column that specifies the record of the last Session record of each customer. As you can imagine, the Sessions table can contain many records for a single Clients record.

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

+3


source to share


2 answers


I may be missing something really obvious, but this is really a really basic sql type you will find in the 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

      

+3


source


It is so simple.



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

+1


source







All Articles