🙏 We need your help! SQLtest.online has no ads and lives only on donations. Even a small amount helps. Donate now →
SQL code copied to buffer
Task 230:

Gap to the Next Smaller Order

SQL Server 2022
The analyst sorts all orders of SalesOrderHeader by TotalDue from the largest and looks for big jumps between neighboring orders.
Output the columns SalesOrderNumber, TotalDue, next_smaller (the TotalDue of the next order in this list) and gap (the difference between the two), sorted by TotalDue from the largest. The last order has no next one: both columns are NULL there.
Expected result Columns: 4 · Rows: 32
SalesOrderNumber TotalDue next_smaller gap

Sample rows open after wrong checks: 0 of 2

Write your query below and click "Check it!". Tables are described in the right pane.

Tutorial

By checking a query, you agree that it is stored without your account details and may be included in anonymized datasets, including for AI training. Learn more

The query result will appear here. Ctrl+Enter - Run query