I have a set of records in a db table like this. The thing that logically links these records is guid1 and guid2 but not all records in the table have a full reference to guid1 and guid2. I'd like to be able to group the records based on the guid1/guid2 link and order them by timestamp asc. So this table ...
timestamp guid1 guid2 text
2022-05-06T10:00:31.5767324Z | cb73c58e-e36b-4fe3-8663-33027ba2afc7 | null | abc1
2022-05-06T10:00:31.5767324Z | ec5d1b9395444a06a36130a9d62ae2c5 | null | abc2
2022-05-06T10:01:31.5767324Z | cb73c58e-e36b-4fe3-8663-33027ba2afc7 | b7ef78cde158437fb65a6878ca908751| def1
2022-05-06T10:01:31.5767324Z | ec5d1b9395444a06a36130a9d62ae2c5 | 206eb977459c4f91bafb9b798f5d60c4| def2
2022-05-06T10:02:31.5767324Z | null | b7ef78cde158437fb65a6878ca908751| ghi1
2022-05-06T10:02:31.5767324Z | null | 206eb977459c4f91bafb9b798f5d60c4| ghi2
... becomes this set of query results
timestamp guid1 guid2 text
2022-05-06T10:00:31.5767324Z | cb73c58e-e36b-4fe3-8663-33027ba2afc7 | null | abc1
2022-05-06T10:01:31.5767324Z | cb73c58e-e36b-4fe3-8663-33027ba2afc7 | b7ef78cde158437fb65a6878ca908751| def1
2022-05-06T10:02:31.5767324Z | null | b7ef78cde158437fb65a6878ca908751| ghi1
2022-05-06T10:00:31.5767324Z | ec5d1b9395444a06a36130a9d62ae2c5 | null | abc2
2022-05-06T10:01:31.5767324Z | ec5d1b9395444a06a36130a9d62ae2c5 | 206eb977459c4f91bafb9b798f5d60c4| def2
2022-05-06T10:02:31.5767324Z | null | 206eb977459c4f91bafb9b798f5d60c4| ghi2
CodePudding user response:
I'm nore sure I fully understand your criteria, however the following produces your desired results:
select *
from t
order by Row_Number() over(partition by [timestamp] order by [timestamp]),
guid1 desc, guid2;