Dan
Dan

Reputation: 1080

T-SQL Query a matrix table used as LIFO

Following my [question]: T-SQL Query a matrix table for free position I've now trying to handle my matrix table as a LIFO. Each couple of (X,Z) represent a channel in which I can store an element. When I generate a location I'm now using the query provided in the above question and here below.

SELECT x, z, MAX(CASE WHEN disabled = 0 AND occupiedId IS NULL THEN Y ELSE 0 END) firstFreeY
FROM matrix
GROUP BY x, z
ORDER BY x, z;

This is working but it doesn't handle "holes". In fact It's possible that a Disabled flag is removed from the table or an element is manually deleted.

In case my Matrix table will look like this:

X   Z   Y   Disabled    OccupiedId
--------------------------------------------------
1   1   1   0   591
1   1   2   0   NULL
1   1   3   1   NULL
1   1   4   0   524
1   1   5   0   523
1   1   6   0   522
1   1   7   0   484
1   2   1   0   NULL
1   2   2   0   NULL
1   2   3   0   NULL
1   2   4   0   NULL
1   2   5   0   NULL
1   2   6   0   589
1   2   7   0   592 

the result of the above query is:

X   Z   firstFreeY
------------------------
1   1   2
1   2   5

instead of:

X   Y   firstFreeY
------------------------
1   1   0
1   2   5

Any suggestions on how to achieve this?

Upvotes: 2

Views: 721

Answers (2)

fnurglewitz
fnurglewitz

Reputation: 2127

just to know if i understood what you were asking, is this working too?

select distinct
m1.x,m1.z, o.y
from
  matrix m1
cross apply
(
  select top 1 (case when m2.Disabled = 0 then m2.y else 0 end)
  from matrix m2
  where
        m1.x = m2.x
    and m1.z = m2.z
    and m2.OccupiedId is null
  order by m2.y desc
) o (y);

Upvotes: 1

Andomar
Andomar

Reputation: 238246

This query looks for the largest Y that is smaller than all other occupied Y's:

select  m1.X
,       m1.Z
,       max(
        case
        when m2.MinOccupiedY is null or m1.Y < m2.MinOccupiedY then m1.Y
        else 0
        end
        ) as FirstFreeY
from    matrix m1
join    (
        select  X
        ,       Z
        ,       min(
                case 
                when disabled <> 0 or occupiedId is not null then Y
                end
                ) as MinOccupiedY
        from    matrix 
        group by
                X
        ,       Z
        ) m2
on      m1.X = m2.X
        and m1.Z = m2.Z
group by
        m1.X
,       m1.Z

Live example at SQL Fiddle.

Upvotes: 2

Related Questions