|
| 1 | +-- Created by Kollil, Oct 2025 |
| 2 | +-- This query is a variation of the same one in the folder, but, with a date as parameter |
| 3 | + |
| 4 | +PARAMETERS(SnapshotDate TIMESTAMP) |
| 5 | + |
| 6 | +SELECT |
| 7 | + CASE WHEN c.cage IS NULL THEN c.room ELSE (c.room || '-' || c.cage) END AS location, |
| 8 | + c.room, |
| 9 | + c.cage, |
| 10 | + c.cagePosition.row, |
| 11 | + c.cagePosition.columnIdx, |
| 12 | + c.cage_type, |
| 13 | + lc.cage AS lowerCage, |
| 14 | + lc.cage_type AS lower_cage_type, |
| 15 | + lc.divider AS divider, |
| 16 | + CASE |
| 17 | + WHEN c.cage_type = 'No Cage' THEN FALSE |
| 18 | + WHEN COALESCE(lc.divider.countAsSeparate, TRUE) = FALSE THEN FALSE |
| 19 | + ELSE TRUE |
| 20 | + END AS isAvailableStructure, |
| 21 | + CASE WHEN c.status IS NOT NULL AND c.status = 'Unavailable' THEN 1 ELSE 0 END AS isMarkedUnavailable, |
| 22 | + -- Example: occupancy "as of" SnapshotDate from study.housing |
| 23 | + CASE WHEN h.Id IS NOT NULL THEN 1 ELSE 0 END AS isOccupiedAsOf, |
| 24 | + -- Echo the effective date we used (handy for debugging) |
| 25 | + COALESCE(SnapshotDate, NOW()) AS AsOfDate |
| 26 | + |
| 27 | +FROM ehr_lookups.cage AS c |
| 28 | + |
| 29 | +-- left-hand neighbor (structural) |
| 30 | + LEFT JOIN ehr_lookups.cage AS lc |
| 31 | + ON c.room = lc.room |
| 32 | + AND c.cagePosition.row = lc.cagePosition.row |
| 33 | + AND c.cagePosition.columnIdx - 1 = lc.cagePosition.columnIdx |
| 34 | + AND lc.cage_type <> 'No Cage' |
| 35 | + |
| 36 | +-- time-varying occupancy example (adjust table/columns to your schema): |
| 37 | + LEFT JOIN study.housing AS h |
| 38 | + ON h.room = c.room |
| 39 | + AND ( (h.cage IS NULL AND c.cage IS NULL) OR h.cage = c.cage ) |
| 40 | + -- "as of" predicate using the parameter |
| 41 | + AND h.date <= COALESCE(SnapshotDate, NOW()) |
| 42 | + AND (h.enddate IS NULL OR h.enddate > COALESCE(SnapshotDate, NOW())) |
| 43 | + |
| 44 | +WHERE c.room.housingType.value = 'Cage Location' |
0 commit comments