Это то, что вы ищете?
SELECT *
FROM T
WHERE LastYardBay = '005'
UNION
SELECT '007',
T1.LastYardRow,
ISNULL(T2.MaxTier, 0)
FROM
(
SELECT *
FROM T
WHERE LastYardBay = '005'
) T1
LEFT JOIN
(
SELECT *
FROM T
WHERE LastYardBay = '007'
) T2
ON T1.LastYardRow = T2.LastYardRow;
Возвращает:
+-------------+-------------+---------+
| LastYardBay | LastYardRow | MaxTier |
+-------------+-------------+---------+
| 005 | 00A | 3 |
| 005 | 00B | 4 |
| 005 | 00C | 1 |
| 005 | 00D | 1 |
| 005 | 00E | 1 |
| 005 | 00F | 4 |
| 005 | 00G | 1 |
| 007 | 00A | 0 |
| 007 | 00B | 0 |
| 007 | 00C | 0 |
| 007 | 00D | 0 |
| 007 | 00E | 5 |
| 007 | 00F | 4 |
| 007 | 00G | 1 |
+-------------+-------------+---------+
Демонстрация в реальном времени
UPDATE:
Поскольку у вас уже есть '005'
, вам нужно просто CROSS JOIN
, а затем отфильтровать с IS NULL
как
WITH A AS
(
SELECT T1.LastYardBay LYB1,
T1.LastYardRow LYR1,
T1.MaxTier MT1,
T2.LastYardBay LYB2,
T2.LastYardRow LYR2,
T2.MaxTier MT2
FROM
(
SELECT *
FROM T
WHERE LastYardBay = '005'
) T1
CROSS JOIN
(
SELECT *
FROM T
WHERE LastYardBay != '005'
) T2
)
SELECT *
FROM T
WHERE LastYardBay = '005'
UNION
SELECT LYB2,
LYR1,
CASE WHEN LYR2 = LYR1 THEN MT2 ELSE 0 END MT
FROM A LEFT JOIN T ON A.LYB2 IS NULL;