对于表中不存在的行,我想为MAX_TIER返回0
到目前为止,这是我的代码:
SELECT
LAST_YARD_BAY, LAST_YARD_ROW, MAX(LAST_YARD_TIER) as MAX_TIER
FROM
Handlift
WHERE
HDCHKOUTD_OUT IS NULL
AND LIFLAG = 'A'
AND LAST_YARD_PARK = 'J1'
GROUP BY
LAST_YARD_BAY, LAST_YARD_ROW
ORDER BY
LAST_YARD_BAY, LAST_YARD_ROW;
屏幕截图显示了部分结果:
对于海湾005
,我有MAX_TIER
,行00A
至00G
,但是对于海湾007
,我只有3行:00E
,00F
和00G
。
对于海湾{{1}的4个缺失行(MAX_TIER
,00A
,00B
和00C
,如何为00D
填充值为0的值}}和其他缺少的行?
答案 0 :(得分:1)
使用CROSS JOIN
生成行,使用LEFT JOIN
生成结果:
SELECT lyb.LAST_YARD_BAY, lyr.LAST_YARD_ROW,
COALESCE(MAX(LAST_YARD_TIER), 0) as MAX_TIER
FROM (SELECT DISTINCT LAST_YARD_BAY FROM Handlift) lyb CROSS JOIN
(SELECT DISTINCT LAST_YARD_ROW FROM Handlift) lyr LEFT JOIN
Handlift hl
ON hl.LAST_YARD_BAY = lyb.LAST_YARD_BAY AND
hl.LAST_YARD_ROW = lyr.LAST_YARD_ROW AND
hl.HDCHKOUTD_OUT IS NULL AND
hl.LIFLAG = 'A' AND
hl.LAST_YARD_PARK = 'J1'
GROUP BY lyb.LAST_YARD_BAY, lyr.LAST_YARD_ROW
ORDER BY lyr.LAST_YARD_BAY, lyr.LAST_YARD_ROW;
我不确定过滤应该如何工作。您可能希望将结果限制在子查询中,以便它们过滤您获得的托架和行。
答案 1 :(得分:1)
您在寻找什么吗?
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 |
+-------------+-------------+---------+
更新:
由于您已经拥有'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;