简体   繁体   中英

SQL Server: Two Level Sort (Order/Group By??)

Everyone:

I have the following code which produced the below table:

SELECT DISTINCT a.[Date]
               ,a.[ID]
               ,a.[Account]
               ,a.[First_Last]
FROM [Table] AS a
WHERE [First_Last] = 1 OR
      [First_Last] = (
                        SELECT MAX([First_Last])
                        FROM [Table] AS b
                        WHERE a.[ID] = b.[ID] AND a.[Account] = b.[Account]
                       )
ORDER BY [ID], [Account], [Date]
Date        ID      Account  First_Last
10/31/2018  1111    45       1
1/29/2021   1111    45       4
9/29/2017   1111    753      1
9/28/2018   1111    753      2
9/29/2017   2222    481      1
1/31/2018   2222    481      2
10/31/2017  2222    488      1
1/31/2018   2222    488      2
11/30/2017  2222    582      1
1/31/2019   2222    582      3
2/28/2017   2222    621      1
2/28/2018   2222    621      2
6/30/2017   2222    1007     1
6/29/2018   2222    1007     2

But I need it to be ordered this way:

Date        ID      Account  First_Last
9/29/2017   1111    753      1
9/28/2018   1111    753      2
10/31/2018  1111    45       1
1/29/2021   1111    45       4
2/28/2017   2222    621      1
2/28/2018   2222    621      2
6/30/2017   2222    1007     1
6/29/2018   2222    1007     2
9/29/2017   2222    481      1
1/31/2018   2222    481      2
10/31/2017  2222    488      1
1/31/2018   2222    488      2
11/30/2017  2222    582      1
1/31/2019   2222    582      3

Notice that the table I need is not sorted by Account . It is sorted by Date for each ID - Account combination. For example, for ID = 1111, Account 753 comes before Account 45 because 753's first date is 9/29/2017 and 45's first date is 10/31/2018. Since I do not want Account to be sorted, I tried to remove Account from the ORDER BY , but that put the Account numbers in random lines because of Date instead of grouping them together.

What am I missing?

Thank you.

You can use window function to find the "first date" by ID and Account .

order by ID, 
         min([Date]) over(partition by ID, Account), 
         [Date]

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