T-SQL查询用作LIFO的矩阵表

时间:2012-11-14 09:52:55

标签: sql sql-server sql-server-2008 tsql

关注我的[问题]:T-SQL Query a matrix table for free position 我现在尝试将矩阵表作为LIFO来处理。每对(X,Z)代表一个我可以存储元素的通道。当我生成一个位置时,我现在正在使用上述问题中提供的查询,如下所示。

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;

这是有效的,但它不处理“漏洞”。实际上,可能会从表中删除“禁用”标志,或者手动删除元素。

如果我的Matrix表格如下:

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 

上述查询的结果是:

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

而不是:

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

有关如何实现这一目标的任何建议吗?

2 个答案:

答案 0 :(得分:2)

此查询查找小于所有其他占用Y的最大Y:

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.

答案 1 :(得分:1)

只是要知道我是否明白你在问什么,这也有效吗?

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);