在 sql bigquery 中查找 X

Finding X in sql bigquery

我们有 6 个变量,每个变量的特定组合应该最接近一个数字。 例如:

60 x1 +226 x2 + 400 x3 +554 x4+ 469 x5+ 278 x6 应该尽可能接近给定的数字,比如 2620

约束:x1>=x2>=x3>=x4>=x5>=x6 Xs只能是整数,也应该>=1

在 Google bigquery

中寻找易于扩展的解决方案

以下适用于 BigQuery 标准 SQL

#standardSQL
WITH puzzle AS (
  SELECT 'x1' x, 60 weight, 2620 target UNION ALL
  SELECT 'x2', 226, 2620 UNION ALL
  SELECT 'x3', 400, 2620 UNION ALL
  SELECT 'x4', 554, 2620 UNION ALL
  SELECT 'x5', 469, 2620 UNION ALL
  SELECT 'x6', 278, 2620 
), numbers AS (
  SELECT num FROM (
    SELECT DIV(ANY_VALUE(target), MIN(weight)) max_num
    FROM puzzle
  ), UNNEST(GENERATE_ARRAY(1, max_num)) num
)
SELECT x1.num x1, x2.num x2, x3.num x3, x4.num x4, x5.num x5, x6.num x6,
  (SELECT weight FROM puzzle WHERE x = 'x1') * x1.num + 
  (SELECT weight FROM puzzle WHERE x = 'x2') * x2.num + 
  (SELECT weight FROM puzzle WHERE x = 'x3') * x3.num + 
  (SELECT weight FROM puzzle WHERE x = 'x4') * x4.num + 
  (SELECT weight FROM puzzle WHERE x = 'x5') * x5.num + 
  (SELECT weight FROM puzzle WHERE x = 'x6') * x6.num AS result
FROM puzzle z,
  numbers x1,
  numbers x2,
  numbers x3,
  numbers x4,
  numbers x5,
  numbers x6
WHERE x1.num >= x2.num 
AND x2.num >= x3.num 
AND x3.num >= x4.num 
AND x4.num >= x5.num 
AND x5.num >= x6.num 
ORDER BY ABS(target - result)   
LIMIT 1

输出为

Row x1  x2  x3  x4  x5  x6  result   
1   4   3   1   1   1   1   2619     

注意:对于参数变量的动态数量,上述方法可以相对容易地采用