Skip to content
Advertisement

Group by one Column in Sql Server and Order by Another Column not contained in either an aggregate function or the GROUP BY clause

i have table “ApplicationEventsSearch” with two column Keyword and EventDate i want to have a query that return result as distinct keyword , but ordered asc by EventDate i have tried many combination , but none worked

Data

Keyword EventDate
123457  2020-09-01
123457fdfdfdfd  2020-09-01
123457fdfdfdfd  2020-09-02
123457fdfdfdfd  2020-09-03

Desired Result

1-123457fdfdfdfd,
2-123457

and what i have tried so far

SELECT 
       [Keyword],EventDate
  FROM [NavaarDb-Dev].[dbo].[ApplicationEventsSearch]
  group by Keyword,EventDate
 order by EventDate


SELECT 
      distinct [Keyword],EventDate
  FROM [NavaarDb-Dev].[dbo].[ApplicationEventsSearch]
  group by Keyword,EventDate
 order by EventDate

Advertisement

Answer

Aren’t you after just MIN or MAX in the ORDER BY?

SELECT Keyword
FROM dbo.YourTable
GROUP BY KeyWord
ORDER BY MAX(EventDate) ASC;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement