我在英国一家受欢迎的零售商工作。我需要编写一个SQL语句,它给出了给定范围与相同范围之间空位置总数之间的拾取位置总数。
我已设法为每个查询编写查询,但我不知道如何在同一查询中编写查询。
第一个是位置总数。
SELECT lh.aisle, count(lh.aisle)
FROM locn_hdr lh
WHERE lh.LOCN_CLASS = 'A'
AND lh.BAY BETWEEN '0030' AND '0230'
AND lh.PICK_DETRM_ZONE LIKE 'HG%'
AND lh.AISLE <= 'QA'
GROUP BY lh.AISLE
ORDER BY lh.AISLE;
这给出了以下结果。
Aisle Count of Locations
I1 164
IA 164
IB 164
IC 164
ID 164
等......有一长串的过道,所以我只展示了前5个。
第二个SQL是
SELECT lh.AISLE, COUNT(lh.AISLE)
FROM LOCN_HDR lh
LEFT OUTER JOIN wm_inventory wi ON wi.location_id = lh.locn_id AND wi.on_hand_qty > '0'
WHERE lh.LOCN_CLASS = 'A'
AND lh.BAY BETWEEN '0030' AND '0230'
AND lh.PICK_DETRM_ZONE LIKE 'HG%'
AND lh.AISLE <= 'QA'
AND wi.location_id IS NULL
GROUP BY lh.AISLE
ORDER BY lh.AISLE;
结果如下:
Aisle Count of Empties
I1 17
IA 54
IB 53
IC 46
ID 38
我想要的表是:
Aisle Count Of locations Count of Empties
I1 164 17
IA 164 54
我希望有一个简单的方法可以做到这一点。
答案 0 :(得分:1)
您可以继续使用查询,但这与实际解决方案相距甚远。只需使用CASE EXPRESSION
添加条件聚合:
SELECT lh.AISLE,
COUNT(lh.AISLE) as cnt1,
COUNT(CASE WHEN wi.location_id IS NULL THEN 1 END) as cnt2
FROM LOCN_HDR lh
LEFT OUTER JOIN wm_inventory wi ON wi.location_id = lh.locn_id AND wi.on_hand_qty > '0'
WHERE lh.LOCN_CLASS = 'A'
AND lh.BAY BETWEEN '0030' AND '0230'
AND lh.PICK_DETRM_ZONE LIKE 'HG%'
AND lh.AISLE <= 'QA'
GROUP BY lh.AISLE
ORDER BY lh.AISLE;
答案 1 :(得分:0)
一种方法是在EXISTS
子句中使用带有子查询的SELECT
:
SELECT lh.aisle, count(lh.aisle) as cnt1,
SUM(CASE WHEN EXISTS (SELECT 1
FROM wm_inventory wi
WHERE wi.location_id = lh.locn_id AND wi.on_hand_qty > 0
THEN 1 ELSE 0
END) as cnt2
FROM locn_hdr lh
WHERE lh.LOCN_CLASS = 'A' AND
lh.BAY BETWEEN '0030' AND '0230' AND
lh.PICK_DETRM_ZONE LIKE 'HG%' AND
lh.AISLE <= 'QA'
GROUP BY lh.AISLE
ORDER BY lh.AISLE;
注意:我猜测on_hand_qty
是一个数字;因此,我删除了'0'
中的单引号。应将数字与数字进行比较;字符串到字符串。
答案 2 :(得分:0)
也许您的第二个查询的直接变化会给出您需要的答案吗?
SELECT lh.AISLE
, COUNT(lh.AISLE) total_aisles
, sum(case when wi.location_id IS NULL then 1 else 0 end) empty_aisles
FROM LOCN_HDR lh
LEFT OUTER JOIN wm_inventory wi ON wi.location_id = lh.locn_id AND wi.on_hand_qty > 0
WHERE lh.LOCN_CLASS = 'A'
AND lh.BAY BETWEEN '0030' AND '0230'
AND lh.PICK_DETRM_ZONE LIKE 'HG%'
AND lh.AISLE <= 'QA'
GROUP BY lh.AISLE
ORDER BY lh.AISLE;