Posted on 2014-12-07
Last Modified: 2014-12-07
I have a table "records": id (identity), date (datetime), activityType (integer) with several entries.
I want the three latest activityType, records sorted by date:

Something like:
SELECT TOP 3 DISTINCT activityType FROM records ORDER BY date DESC
Question by:fmsol
  • 3
  • 2
LVL 34

Expert Comment

by:Mike Eghtebas
ID: 40485711
SELECT TOP 3 id, activityType FROM records Grouped By Id, activityType ORDER BY date DESC

Author Comment

ID: 40485728
SELECT TOP 3 id, activityType FROM records Group By Id, activityType ORDER BY date DESC
Column "date" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause
LVL 34

Expert Comment

by:Mike Eghtebas
ID: 40485730
SELECT TOP 3 id, activityType, [date] FROM records Grouped By Id, activityType,  [date] ORDER BY [date] DESC
Backup Solution for AWS

Read about how CloudBerry Backup fully integrates your backups with Amazon S3 and Amazon Glacier to provide military-grade encryption and dramatically cut storage costs on any platform.


Author Comment

ID: 40485732
Not there yet; since date is different, it doesn't return distinct activityType
LVL 34

Expert Comment

by:Mike Eghtebas
ID: 40485739
re:> since date is different

Could you give more info on this statement? Why and how different?
LVL 18

Accepted Solution

Simon earned 500 total points
ID: 40485744
select top 3 * from (select activityType,max(date)  as LatestDate from records group by activityType)
order by LatestDate DESC

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

761 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question