I'm trying to build a query for a matrix table which has a schema like this:
X | Y | Z | Disabled | OccupiedId |
--------------------------------------------
1 1 1 0 NULL
1 2 1 0 NULL
1 3 1 1 NULL
1 4 1 0 1
1 5 1 0 2
1 6 1 0 3
1 7 1 0 4
1 1 2 0 NULL
1 2 2 0 NULL
1 3 2 0 NULL
1 4 2 0 NULL
1 5 2 0 NULL
1 6 2 0 NULL
1 7 2 0 NULL
I want to group for X, Z and find the first available position on Y. Available by all means is NOT Disabled and NOT Occupied.
In the example provided this query should return:
X | Z | FreeY
--------------------------------------------
1 1 2
1 2 7
The query should select the first free Y (or the last occupied Y) considering that each (X, Z) are filled starting from the end (MAX Y is constant)
I've tried different approach unsuccessfully :( Any suggestions is highly appreciated! Kind Regards, D.
SQL fiddle
For your edit (disabled=bit column), this query shows lastOccupiedID as well as firstFreeY
SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
Results: