简体   繁体   中英

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...

在此输入图像描述

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

Thank you so much for your help.

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

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.

Have you tried to add Order By PersonID, Date_Time in the end of your select statement ?

Please note that sorting the Date_Time column will not work for you as expected if it is a string and not a Date field.

Provide a code sample of what you did so far so that we will be able to understand your problem more clearly so that we cab help you more efficiently.

    SELECT Date_Time,PersonID,[Status] 
    FROM TABLE1
    GROUP BY Date_Time,PersonID,[Status] 
    ORDER BY PersonID,Date_Time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM