Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Group By Order By Where

I have a single table which I need to pull back the 5 most recent records based on a userID and keying off of documentID (no duplicates). Basically, I'm tracking visited pages and trying to pull back the 3 most recent by user.

Sample data:

╔══════════════════════════════════════════════╗
║UserID   DocumentID   CreatedDate             ║
╠══════════════════════════════════════════════╣
║  71         22       2013-09-09 12:19:37.930 ║
║  71         25       2013-09-09 12:20:37.930 ║
║  72          1       2012-11-09 12:19:37.930 ║
║  99         76       2012-10-10 12:19:37.930 ║
║  71         22       2013-09-09 12:19:37.930 ║
╚══════════════════════════════════════════════╝

Desired query results if UserID = 71:

╔══════════════════════════════════════════════╗
║UserID    DocumentID  CreatedDate             ║
╠══════════════════════════════════════════════╣
║  71         25       2013-09-09 12:20:37.930 ║
║  71         22       2013-09-09 12:19:37.930 ║
╚══════════════════════════════════════════════╝
like image 783
JGrimm Avatar asked Sep 09 '13 17:09

JGrimm


People also ask

What is the order of WHERE GROUP BY and ORDER BY?

GROUP BY is always placed after the WHERE clause but before the ORDER BY statement.

Can I use GROUP BY and WHERE together in SQL?

Absolutely. It will result in filtering the records on your date range and then grouping it by each day where there is data.

Which comes first GROUP BY or WHERE?

Using Group By and Order By TogetherThe GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

Can we use ORDER BY with WHERE clause in SQL?

You can use the WHERE clause with or without the ORDER BY statement. You can filter records by finite values, comparison values or with sub-SELECT statements.


2 Answers

SELECT TOP 3 UserId, DocumentId, MAX(CreatedDate)
FROM MyTable
WHERE UserId = 71
GROUP BY UserId, DocumentId
ORDER BY MAX(CreatedDate) DESC
like image 100
Tom Avatar answered Oct 04 '22 02:10

Tom


You could try using a CTE and ROW_NUMBER.

Something like

;WITH Vals AS (
    SELECT UserID, 
           DocumentID, 
           ROW_NUMBER() OVER(PARTITION BY UserID, DocumnentID ORDER BY CreatedDate DESC) RowID
    FROM MyTable
)
SELECT TOP 3 *
FROM Vals
WHERE UserID = 71
AND RowID = 1
like image 28
Adriaan Stander Avatar answered Oct 04 '22 03:10

Adriaan Stander