sql >> Databasteknik >  >> RDS >> Sqlserver

T-SQL Fråga en matristabell för ledig position

SQL-fiol

 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


  1. Plugin 'FEDERATED' är inaktiverad

  2. Hur ser man loggfiler i MySQL?

  3. PostgreSQL- Filtrera ett datumintervall

  4. Pivottabeller i MySQL