简体   繁体   English

雪花中的子查询与未知匹配,与列匹配

[英]Subquery in snowflake with unknown matches, matches to columns

I have a few tables that I'm joining and one of them can have an unknown number of matches, up to 6. Each match should be returned as a row value in the initial query.我有几个要加入的表,其中一个可以有未知数量的匹配项,最多 6 个。每个匹配项都应作为初始查询中的行值返回。 For example:例如:

SELECT a.ID, a.match1, a.match2, a.match3, a.match4, a.match5, a.match6
FROM table1 a, (SELECT ID, match FROM table2 WHERE a.ID = table2.ID) b
WHERE a.ID = b.ID

That's probably not the right syntax but hopefully it shows what I need.这可能不是正确的语法,但希望它能显示我需要的东西。 So the nested query MAY return 1 match or 5. Each match should be the value for the corresponding column name, ie a.match1 = first match, b.match2 = second match, etc etc.所以嵌套查询可能返回 1 个匹配项或 5 个匹配项。每个匹配项应该是对应列名的值,即 a.match1 = 第一个匹配项,b.match2 = 第二个匹配项,等等。

Please let me know if I need to explain further.如果我需要进一步解释,请告诉我。 I know this isn't the optimal schema to use but it's what I was told to work with.我知道这不是使用的最佳模式,但它是我被告知要使用的。

Something that SQL doesn't like is an unknown number of columns. SQL 不喜欢的东西是未知数量的列。

As a quick hack, you could aggregate all matches in an array, and then have a query around it transforming the matches into a predefined (large) number of columns.作为一个快速破解,您可以将所有匹配项聚合到一个数组中,然后围绕它进行查询,将匹配项转换为预定义的(大量)列。

Like this:像这样:

with data as (
select $1 id
from (values(1),(2))
), data2 as (
select $1 id, $2 match
from (values(1, 'a1'),(1, 'a2'),(2, 'b1'),(2, 'b2'),(2, 'b3'))
)

select id, matches[0], matches[1], matches[2], matches[3]
from (
    select a.id, array_agg(match) matches
    from data a
    join data2 b
    on a.id=b.id
    group by 1
);

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM