lneville
Starting Member
12 Posts |
Posted - 2013-11-14 : 11:21:04
|
The cells in an N-dimensional space are modelled with the 2 tables below. A script is needed that takes a single cell (by CellID) and returns all the other cells that are "inline" with the given cell along each axis (including itself). For example, suppose the space has 3 dimensions (X, Y, Z) and X has 2 positions, Y has 2 and Z has 3. If the cell with coordinates {1,1,1} is given, the result should be: +----------+---------+ | AxisCode | Cell | +----------+---------+ | X | {1,1,1} | <- showing coordinates for clarity, but should be CellID | X | {2,1,1} | | Y | {1,1,1} | | Y | {1,2,1} | | Z | {1,1,1} | | Z | {1,1,2} | | Z | {1,1,3} | +----------+---------+I have spent hours on this and only come up with queries that are hard-coded for a specific number of dimensions ....Please note:**Changing the schema of the 2 tables is not an option!The script has to work for N dimensions, and should not involve loops or cursors.**Compatibility must be MS SQL 2008 R2Any ideas gratefully received!create table dbo.Cells( CellID int not null, CellValue int not null, constraint PK_Cells primary key (CellID) )create table dbo.AxisPositions( AxisCode char(1) not null, -- X, Y, Z etc PositionOnAxis int not null, -- 1, 2, 3, 4 etc constraint PK_AxisPositions primary key (AxisCode, PositionOnAxis) )create table dbo.CellAxes( CellID int not null, AxisCode char(1) not null, -- X, Y, Z etc PositionOnAxis int not null, -- 1, 2, 3, 4 etc constraint PK_CellAxes primary key (CellID, AxisCode), constraint FK_CellAxes_Cells foreign key (CellID) references Cells(CellID), constraint FK_CellAxes_AxisPositions foreign key (AxisCode, PositionOnAxis) references AxisPositions(AxisCode, PositionOnAxis) )-- Example datainsert Cells (CellID, CellValue)values (1, 67), (2, 45), (3, 0), (4, 4), (5, 78), (6, 213), (7, 546), (8, 455), (9, 12), (10, 67), (11, 4), (12, 5)insert AxisPositions (AxisCode, PositionOnAxis)values ('X', 1), ('X', 2), ('Y', 1), ('Y', 2), ('Z', 1), ('Z', 2), ('Z', 3)insert CellAxes (CellID, AxisCode, PositionOnAxis)values (1, 'X', 1), (1, 'Y', 1), (1, 'Z', 1), (2, 'X', 2), (2, 'Y', 1), (2, 'Z', 1), (3, 'X', 1), (3, 'Y', 2), (3, 'Z', 1), (4, 'X', 2), (4, 'Y', 2), (4, 'Z', 1), (5, 'X', 1), (5, 'Y', 1), (5, 'Z', 2), (6, 'X', 2), (6, 'Y', 1), (6, 'Z', 2), (7, 'X', 1), (7, 'Y', 2), (7, 'Z', 2), (8, 'X', 2), (8, 'Y', 2), (8, 'Z', 2), (9, 'X', 1), (9, 'Y', 1), (9, 'Z', 3), (10, 'X', 2), (10, 'Y', 1), (10, 'Z', 3), (11, 'X', 1), (11, 'Y', 2), (11, 'Z', 3), (12, 'X', 2), (12, 'Y', 2), (12, 'Z', 3) |
|