Sqlserver
 sql >> Teknologi Basis Data >  >> RDS >> Sqlserver

T-SQL Query tabel matriks untuk posisi gratis

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


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. SUBSTRING vs KIRI di SQL SERVER

  2. Mengapa Prosedur Tersimpan lebih cepat daripada Query

  3. Apa representasi internal dari datetime di sql server?

  4. Kunci asing ke kunci komposit

  5. T-SQL trim   (dan karakter non-alfanumerik lainnya)