Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a sql query to Sort or Group the dataset

I have data in a table A as shown below. I want to group memberID as one set and sort the Date_Time in each set as shown in snapshot below

Date_Time        PersonID     Status
4/2/14 10:15 AM    ghi        Closed
4/1/14 9:15 AM     ghi        Cancelled
4/1/14 11:00 AM    abc        Cancelled
4/2/14 8:12 AM     def        Closed
4/1/14 9:17 AM     def        Hold
4/3/14 2:17 PM     abc        Hold
4/2/14 8:30 AM     abc        Open
4/3/14 8:16 AM     jkl        Closed
4/1/14 12:10 PM    jkl        Open
4/1/14 11:30 AM    abc        Hold

The final example-snapshot attached below you will see memberID: ghi first row date time ‘4/1/2014 9:15:00 AM’ is greater than memberID: def 1st row date_Time ‘4/1/2014 9:17:00 AM’ highlighted in yellow. And that is the main reason memberID ghi set tweaks as first set and then follows by memberID def set and then meberID abc, jkl etc...

enter image description here

Could some one please help me how to write MS-SQL query to achieve the final result.

Thank you so much for your help.

like image 851
desi Avatar asked Dec 05 '25 14:12

desi


2 Answers

If I'm understanding your question correctly, you need to join the table back to itself using the min aggregate to establish a sort order:

select t.*
from yourtable t
  join (
    select personid, 
      min(date_time) min_date_time
    from yourtable
    group by personid
    ) t2 on t.personid = t2.personid
order by t2.min_date_time, t.date_time
  • SQL Fiddle Demo
like image 153
sgeddes Avatar answered Dec 07 '25 03:12

sgeddes


Here's another way:

SELECT
  Date_Time,
  PersonID,
  Status
FROM
  dbo.atable
ORDER BY
  MIN(Date_Time) OVER (PARTITION BY PersonID),
  PersonID,
  Date_Time
;

The approach, though, is same as in sgeddes's answer, it just has different syntax. It calculates minimum Date_Time values using MIN(...) OVER (...). That makes a join to a derived table completely unnecessary.

One other little difference is that I have added PersonID to the ORDER BY clause to make sure that people with identical minimum Date_Time values do not have their rows mixed up.

like image 34
Andriy M Avatar answered Dec 07 '25 03:12

Andriy M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!