TransWikia.com

Apply group by having order by with latest record

Stack Overflow Asked by MussadiqChhipa on December 9, 2021

I need to group by name column having order by date with the latest group first, for example

Data:

name|status|date
john|read  |07/23/2020
matt|read  |07/23/2020
john|print |07/24/2020
matt|print |07/24/2020

it should be displayed as:

name|status|date
john|print |07/24/2020
john|read  |07/23/2020
matt|print |07/24/2020
matt|read  |07/23/2020

Kindly assist me.

my attempt so far:

;with cte as(
    select status,name, date,
    ROW_NUMBER() OVER(PARTITION BY name ORDER BY date desc) RowID
    from @tbl
)

select status,name,timeStamp from cte
order by timeStamp desc,RowID desc

3 Answers

You can use window functions in the order by. But you probably also want to keep the names together when there are ties, so you need three keys:

order by max(date) over (partition by name) desc,
         name,
         date desc;

Note that you can also use other tie breakers. For instance, when two names have the same most recent date, you can put the one with the most recent earliest date first with an additional key:

order by max(date) over (partition by name) desc,
         min(date) over (partition by name) desc,
         name,
         date desc;

Answered by Gordon Linoff on December 9, 2021

I guess you're looking for

WITH CTE AS
(
  SELECT *, ROW_NUMBER() OVER(PARTITION BY Status ORDER BY [Date]) RN
  FROM
  (
    VALUES
    ('john', 'print', '2020-07-24'),
    ('john', 'read', '2020-07-23'),
    ('matt', 'print', '2020-07-24'),
    ('matt', 'read', '2020-07-23')
  ) T(Name, Status, [Date])
)
SELECT Name, Status, [Date]
FROM CTE
ORDER BY RN DESC;

Here is a db<>fiddle

Answered by Ilyes on December 9, 2021

You can use window functions:

select *
from mytable t
order by max(date) over(partition by name) desc, date desc

Answered by GMB on December 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP