0

我只是一个初学者,我的简单 SQL 代码有问题。我正在尝试检索不同国家/地区的 outbound-cost-pal 的平均值,并将其写入仓库的每个相应行。

我的代码如下:

INSERT INTO Warehouse (`inbound-cost-pal`)
SELECT cost.`average`
FROM Warehouse AS wh
INNER JOIN (
    SELECT  
    AVG     (`warehouse-cost-table`.`outbound-cost-pal`) AS `average`
    FROM    `warehouse-cost-table` 
            )cost
ON wh.`location-tariff-code` = LEFT(cost.`country`,2)
;

我在“on 子句”中收到错误消息“Unknown column 'cost.country'”。

4

2 回答 2

0

如果您需要每个国家/地区的 avg() 那么您还需要在子查询中使用国家

INSERT INTO Warehouse (`inbound-cost-pal`)
SELECT cost.`average`
FROM Warehouse AS wh
INNER JOIN (
    SELECT   `warehouse-cost-table`.`country`,
    AVG(`warehouse-cost-table`.`outbound-cost-pal`) AS `average`
    FROM    `warehouse-cost-table` 
    GROUP BY `warehouse-cost-table`.`country`
            ) cost
ON wh.`location-tariff-code` = LEFT(cost.`country`,2)
;

否则,如果您不需要国家/地区的 avg() 而是整体平均,那么您可以使用交叉联接而不是内部联接

INSERT INTO Warehouse (`inbound-cost-pal`)
SELECT cost.`average`
FROM Warehouse AS wh
CROSS JOIN (
    SELECT  
    AVG(`warehouse-cost-table`.`outbound-cost-pal`) AS `average`
    FROM    `warehouse-cost-table` 
            ) cost
  ;

你应该避免函数名和括号之间的空格.. AVG()

于 2019-11-12T13:35:25.253 回答
0

You forgot country in the select of subquery cost

INSERT INTO Warehouse (inbound-cost-pal)
SELECT cost.average
FROM Warehouse AS wh
INNER JOIN (
    SELECT  
    AVG     (warehouse-cost-table.outbound-cost-pal) AS average,
            country
    FROM    warehouse-cost-table 
            )cost
ON wh.location-tariff-code = LEFT(cost.country,2)
;
于 2019-11-12T13:34:25.373 回答