How can I insert many field values under one term?
You needn't have to do aggregation via temporary tables, it can be done in your query via a GROUP_CONCAT expression &amp; GROUP clause:

$query = \Drupal::database()-&gt;select("excel","m")-&gt;fields("m",["stokkodu","grupadi"])-&gt;condition("grupadi", "","!=");
$query-&gt;addExpression('GROUP_CONCAT(m.stokkodu)', 'stokkodus');
$query-&gt;groupBy('m.grupadi');
$results = $query-&gt;execute()-&gt;fetchAll(); 
foreach ($results as $result) {
  $result-&gt;stokkodus contains a comma-delimited list of values that you can split with explode()
  $stokkodus = explode(',');
  // @TODO: add transform logic
}


In the example above, you can transform the exploded array then create an array of values for your multivalue field_stok_kodu field:

  // @TODO: add transform logic
  'field_stok_kodu' =&gt; [
    ['value' =&gt; $stokkodus[0]],
    ['value' =&gt; $stokkodus[1]]
  ];