0

I'm having a problem with my simple SQL code as I'm just a beginner. I'm trying to retrieve the average value of outbound-cost-pal for different countries and write this in every corresponding line of Warehouse.

My code is the following:

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)
;

I'm receiving the error message 'Unknown column 'cost.country' in 'on clause''.

anthony
  • 69
  • 4

2 Answers2

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)
;
i.signori
  • 585
  • 3
  • 16
0

if you need an avg() for each country then you need also country in subquery

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)
;

otherwise if you don't need an avg() for country but the overall avg then you could use cross join instead of inner join

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
  ;

and you should avoid space between function name and brackets .. AVG()

ScaisEdge
  • 131,976
  • 10
  • 91
  • 107