Home > Back-end >  SQL Server: Two Level Sort (Order/Group By??)
SQL Server: Two Level Sort (Order/Group By??)

Time:08-30

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.

CodePudding user response:

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]
  • Related