我的问题是正确的联接不起作用,我猜是由于使用了别名。
我已使用-注释了这些行,以指示最有可能导致此问题的行。如果我单独运行代码的交叉连接部分,则可以正常运行。
如果我添加如下所示的交叉联接,然后使用final_leg表进行右联接a我收到一条错误消息,说“关系“ k”不存在“。
k是我在最后一个select语句中用来调用表的CROSS连接部分的别名。
amqmdnetstd.dll
答案 0 :(得分:2)
该问题很可能是因为您没有为list_legs_ds
子查询中的列加上别名,这意味着您至少有两列具有相同的名称。
这是一个很好的例子,说明了为什么通常不应该使用select *...
以及为什么要在要选择的列中明确显示。请尝试以下操作:
WITH final_leg AS
(SELECT y.*
FROM (SELECT y.shipment_id,
y.route_id,
MAX(leg_sequence_id) max_leg_sequence_id
FROM posimorders.sc_execution_eu.o_detailed_routes_v2 y
GROUP BY 1,
2) AS x
INNER JOIN posimorders.sc_execution_eu.o_detailed_routes_v2 y
ON x.route_id = y.route_id
AND x.shipment_id = y.shipment_id
AND y.leg_sequence_id = x.max_leg_sequence_id),
dest_leg AS
(SELECT y.*
FROM (SELECT y.shipment_id,
y.route_id,
MIN(leg_sequence_id) max_leg_sequence_id
FROM posimorders.sc_execution_eu.o_detailed_routes_v2 y
LEFT JOIN warehouse_attributes w -- Joining to add origin country of origin FC
ON w.warehouse_id = y.leg_warehouse_id
GROUP BY 1,
2) x
INNER JOIN posimorders.sc_execution_eu.o_detailed_routes_v2 y
ON x.route_id = y.route_id
AND x.shipment_id = y.shipment_id
AND y.leg_sequence_id = x.max_leg_sequence_id),
list_legs_ds AS
(SELECT t1.leg_warehouse_id AS leg_ware,
t1.total_packages,
t2.leg_warehouse_id AS last_ds,
t2.destination_country_code
FROM (SELECT leg_warehouse_id AS leg_ware,
SUM(pck_count) AS total_packages
FROM posimorders.sc_execution_eu.o_detailed_routes_v2
GROUP BY 1
HAVING SUM(pck_count) > 50000) t1
CROSS JOIN (SELECT DISTINCT leg_warehouse_id AS last_ds,
destination_country_code
FROM posimorders.sc_execution_eu.o_detailed_routes_v2) t2)
SELECT a.route_warehouse_id,
k.leg_ware,
k.last_ds lm_ds
-- should there be something to aggregate here?
FROM final_leg a
INNER JOIN dest_leg b
ON a.shipment_id = b.shipment_id
AND a.route_id = b.route_id
RIGHT JOIN list_legs_ds k
ON a.leg_warehouse_id = k.leg_ware -- and a.leg_ship_method = k.lm_ds
GROUP BY 1,
2,
3;