I am using SQL Server and I have a table with the following columns:
SessionId | Date | first name | last name
I would like to do group by sessionId
and then get the row with the max date.
For example:
xxx | 21/12/2012 | f1 | l1
xxx | 20/12/2012 | f2 | l2
yyy | 21/12/2012 | f3 | l3
yyy | 20/12/2012 | f4 | l4
I would like to get the following rows:
xxx | 21/12/2012 | f1 | l1
yyy | 21/12/2012 | f3 | l3
Thank you
You can use a SELECT command with a GROUP BY clause to group all rows that have identical values in a specified column or combination of columns, into a single row. You can also find the aggregate value for each group of column values.
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups. This GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY clause.
The SQL GROUP BY clause allows us to group individual data based on defined criteria. You can group individual data by one or more table columns. In order to do the grouping properly, you often need to apply aggregate functions to the column(s) within the SQL SELECT statement.
You can, but the "GROUP BY" clause is used for grouping together sets of rows, so it does not make sense for your question (or anything that involves a "SELECT *").
Try this:
WITH MAXSessions
AS
(
SELECT
*,
ROW_NUMBER() OVER(PARTITION BY SessionID ORDER BY Date DESC) rownum
FROM Sessions
)
SELECT
SessionId,
Date,
firstname,
lastname
FROM MAXSessions
WHERE rownum = 1;
Or:
SELECT
s.SessionId,
s.Date,
s.firstname,
s.lastname
FROM Sessions s
INNER JOIN
(
SELECT SessionID, MAX(Date) LatestDate
FROM sessions
GROUP BY SessionID
) MAxs ON maxs.SessionID = s.SessionID
AND maxs.LatestDate = s.Date;
Update: To get the count of the sessions, you can do this:
SELECT
s.SessionId,
s.Date,
s.firstname,
s.lastname,
maxs.SessionsCount
FROM Sessions s
INNER JOIN
(
SELECT SessionID, COUNT(SessionID), SessionsCount, MAX(Date) LatestDate
FROM sessions
GROUP BY SessionID
) MAxs ON maxs.SessionID = s.SessionID
AND maxs.LatestDate = s.Date;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With