在sqlbigquery中查找x

6g8kf2rb  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(262)

我们有6个变量,每个变量的特定组合应该最接近一个数字。例如: 60 x1 +226 x2 + 400 x3 +554 x4+ 469 x5+ 278 x6 应该尽可能接近一个给定的数字,比如说2620
约束条件: x1>=x2>=x3>=x4>=x5>=x6 xs只能是整数,也应该大于等于1
在googlebigquery中寻找一个易于扩展的解决方案

xzabzqsa

xzabzqsa1#

下面是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

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

相关问题