Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 表2\u数组中表1\u ID的计数_Sql_Presto - Fatal编程技术网

Sql 表2\u数组中表1\u ID的计数

Sql 表2\u数组中表1\u ID的计数,sql,presto,Sql,Presto,我正在使用两张桌子: CREATE TABLE Table1 ( id int, name varchar ) CREATE TABLE Table2 ( id int, name varchar, link array<int> ) 创建表表1 ( id int, 名称varchar ) 创建表2 ( id int, 名字叫瓦查尔, 链路阵列 ) 表2.link包含与表1.id对应的值。我想计算每个Table1.id在Table2.link的实例中出现的次数。在Excel中使

我正在使用两张桌子:

CREATE TABLE Table1
(
id int,
name varchar
)

CREATE TABLE Table2
(
id int,
name varchar,
link array<int>
)
创建表表1
(
id int,
名称varchar
)
创建表2
(
id int,
名字叫瓦查尔,
链路阵列
)
表2.link包含与表1.id对应的值。我想计算每个Table1.idTable2.link的实例中出现的次数。在Excel中使用单元格引用会很简单,但我不知道如何使用SQL查询来实现它。

Presto

select    *
from     (select    l.id           
                   ,count(*)    as cnt
          from      Table2 cross join unnest (link) as l(id)
          group by  l.id     
          ) t2
where     t2.id in (select id from Table1)
order by  id

PostgreSQL演示

create table Table1 (id int);
create table Table2 (arr int[]);

insert into Table1 values 
    (1),(2),(3)
;

insert into Table2 values 
    (array[1,5]),(array[1,3]),(array[1,2,3]),(array[2,3])
   ,(array[1,2,4]),(array[1,2]),(array[1,3,5]),(array[1,2,4])
;



“数组”是什么意思?这不是一种原生的SQL数据类型。@luke.samuel.mccarthy我建议在这里对表进行更详细的描述,或者可以描述表外观的DDL。这将有助于理解这个问题。你能为这两个表发布一些示例吗?任何答案都将是特定于数据库的。你在用什么数据库?@DuduMarkovitz我在用Presto。根据您的回答,看起来“unnest”是我所需要的,尽管实现将涉及到Presto中的交叉连接。请检查执行此操作的Presto版本。非常感谢,非常感谢你的帮助
create table Table1 (id int);
create table Table2 (arr int[]);

insert into Table1 values 
    (1),(2),(3)
;

insert into Table2 values 
    (array[1,5]),(array[1,3]),(array[1,2,3]),(array[2,3])
   ,(array[1,2,4]),(array[1,2]),(array[1,3,5]),(array[1,2,4])
;
select    *
from     (select    unnest(arr) as id             
                   ,count(*)    as cnt
          from      Table2
          group by  id     
          ) t2
where     t2.id in (select id from Table1)
order by  id
+----+-----+
| id | cnt |
+----+-----+
| 1  | 7   |
+----+-----+
| 2  | 5   |
+----+-----+
| 3  | 4   |
+----+-----+