【问题标题】:Presto Sql: How to select the highest ranking value in arrayPresto Sql:如何选择数组中排名最高的值
【发布时间】:2022-01-11 00:11:54
【问题描述】:

我在 table1 中有一个列,每一行都是一个数组,其中的数字代表国家。 表1:

countries    
[15, 20]     
[21, 5]      
[20, 27]     
[1, 21, 60]  

我有一个单独的表 (table2),其中包含一个映射系统,将每个国家/地区编号映射到其排名。

表2

number  rank
5        1
15       2
1        3
20       4
60       5
27       6
21       7

我想在 table1 中生成一个新列,它输出数组中排名最高的值(根据 table2 中的系统)。例如,如果数组是 [20, 21, 5],则这些值在 table2 中的相对排名是 [4, 7, 1],因此输出将为 5(因为 5 排名第一,而 20这是#4和21这是#7。

例子:

countries    answer
[15, 20]     15
[21, 5]      5
[20, 27]     20
[1, 21, 60]  1

我使用此代码在 Presto Sql 中创建了一个地图:

SELECT
    map(ARRAY_AGG(table2.number), ARRAY_AGG(table2.rank))
    FROM table2

我需要能够将其映射到 Table1 中的数组

【问题讨论】:

  • 请详细说明您的算法的工作原理,因为它不够清楚。
  • 我现在添加了更详细的描述。

标签: sql presto


【解决方案1】:

给你,

const ranks = {
  5: 1,
  15: 2,
  1: 3,
  20: 4,
  60: 5,
  27: 6,
  21: 7
};

const findHighestRank = (inputArray) => {
  let rankArray = [];
  let answer = 0;

  inputArray.map((arr, index) => {
    if (ranks[inputArray[index]] !== undefined) {
      return rankArray.push(ranks[inputArray[index]]);
    }
    return null;
  });

  if (rankArray.length > 0) {
    answer = Math.min(...rankArray);
  }

  return answer;
};

let foundRank = findHighestRank([15, 20]);
console.log("Answer >>>", foundRank);

假设你的队伍被放置在对象中。这是沙盒的链接https://codesandbox.io/s/highest-rank-in-array-hy62p?file=/src/index.js:0-506

【讨论】:

  • 如果这能解决您的问题,请投票。
  • 有没有可能在 Presto Sql 中得到这个?
  • 与您要使用的数据库无关,以上代码有效。
  • 我需要能够执行sql中的代码
猜你喜欢
  • 2019-05-21
  • 2023-03-03
  • 2021-12-28
  • 2015-03-24
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
  • 2013-05-04
相关资源
最近更新 更多