2012-11-13 77 views
1

我試圖建立具有這樣的模式的矩陣表的查詢矩陣表:T-SQL查詢的免費位置

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 

我想組X,Z,並找到Y上的第一個可用位置。 可用的所有手段都不禁用和不佔用。

在提供此查詢的例子應該返回:

X | Z | FreeY 
-------------------------------------------- 
1  1  2 
1  2  7 

查詢應選擇第一個自由Y(或最後佔用的Y)考慮到每個(X,Z)充滿從年底開始( MAX Y爲常數)

我已經嘗試不同的方法不成功:( 任何建議高度讚賞! 親切的問候, D.

+1

請發表您嘗試 –

+0

爲什麼是'第1行,3' ='2'? –

+0

對不起,我還在編輯這個例子,因爲它不清楚... – dna2

回答

2

您進行修改(禁用=位列),這個查詢顯示lastOccupiedID以及firstFreeY

select x, z, 
     max(case when disabled=1 or occupiedid is not null 
      then Y else 0 end) lastOccupiedPosition, 
     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; 


SQL Fiddle

MS SQL Server 2008的架構設置

create table matrix(
X int , Y int , Z int , Disabled varchar(5) , OccupiedId int); 
insert matrix values 
(1 , 1 , 1 , 'True'  , NULL  ), 
(1 , 1 , 2 , 'False'  , NULL  ), 
(1 , 1 , 3 , 'False'  , NULL  ), 
(1 , 1 , 4 , 'False'  , NULL  ), 
(1 , 2 , 1 , 'False'  , NULL  ), 
(1 , 2 , 2 , 'False'  , NULL  ), 
(1 , 2 , 3 , 'False'  , 123  ), 
(1 , 2 , 4 , 'False'  , NULL  ); 

查詢1

select x, z, 
     max(case when disabled='true' or occupiedid is not null 
      then Y else 0 end) lastOccupiedPosition 
    from matrix 
group by x, z 
order by x, z 

Results

| X | Z | LASTOCCUPIEDPOSITION | 
-------------------------------- 
| 1 | 1 |     1 | 
| 1 | 2 |     0 | 
| 1 | 3 |     2 | 
| 1 | 4 |     0 | 
+0

這就是它!非常感謝你!! – dna2

3

SQL fiddle

CREATE TABLE Coordinate 
( X int, Y int,Z int, Disabled bit, OccupiedId int) 

INSERT INTO Coordinate VALUES (1,1,1, 1, NULL) 
INSERT INTO Coordinate VALUES (1,1,2, 0, NULL) 
INSERT INTO Coordinate VALUES (1,1,3, 0, NULL) 
INSERT INTO Coordinate VALUES (1,1,4, 0, NULL) 
INSERT INTO Coordinate VALUES (1,2,1, 0, NULL) 
INSERT INTO Coordinate VALUES (1,2,2, 0, NULL) 
INSERT INTO Coordinate VALUES (1,2,3, 0, 123) 
INSERT INTO Coordinate VALUES (1,2,4, 0, NULL) 
INSERT INTO Coordinate VALUES (1,2,5, 1, NULL) 

SELECT X, Z, MIN(Y) AS FirstFreePosition 
FROM Coordinate 
WHERE Disabled = 0 AND OccupiedId IS NULL 
GROUP BY X, Z 

OR -- if you need the unavailable combinations too, then something like this: 

SELECT X, Z, MIN(CASE 
       WHEN Disabled = 1 OR OccupiedId IS NOT NULL 
       THEN 1000 --a big number 
       ELSE Y END) AS FirstFreePosition 
FROM Coordinate 
GROUP BY X, Z