0

我正在努力在雪花模式中创建一个语句。我需要显示所有产品和相关曲目的列表,但还需要在每行中包含歌曲作者姓名和所有权百分比的列表,例如。添加一列,如下所示:“Sam Smith (50.00%)、Sally Simpson (25.00%)、John Chan (25.00%)”。我的桌子是:

Table: PRODUCT -PRODUCT_ID -ALBUM_ARTIST -ALBUM_TITLE

Table: SONGWRITER -SONGWRITER_ID -FIRSTNAME -LASTNAME

Table: SONG_SONGWRITER -SONGWRITER_ID -TRACK_ID -OWNERSHIP_SHARE

Table: TRACK -TRACK_ID -PRODUCT_ID -TRACK_ARTIST |TRACK_NAME

我知道我需要连接(并加入)SONG_SONGWRITER 和 SONGWRITER 表,但由于显示产品和曲目所需的几个连接,我非常迷茫。

我尝试过(但失败了):

SELECT prod.*, tra.TRACK_NAME,(SELECT (SELECT ','+ writer.FIRSTNAME +' ' +writer.LASTNAME + '(' + FORMAT(ssw.OWNERSHIP_SHARE,'P2') + ')' FROM SONGWRITER writer INNER JOIN SONG_SONGWRITER ssw ON ssw.SONGWRITER_ID=writer.SONGWRITER_ID FOR XML PATH ('')))
FROM PRODUCT prod
INNER JOIN TRACK tra
ON tra.PRODUCT_ID=prod.PRODUCT_ID
ORDER BY tra.SEQUENCE;

至于预期的结果,它应该有希望返回如下内容:

PRODUCT_ID | 专辑艺术家 | ALBUM_TITLE | 跟踪名称 | 所有权

1 | 肉饼 | 蝙蝠出地狱 | 蝙蝠出地狱 | 肉饼 (50%),约翰尼词曲作者 (50%

有人可以帮忙吗?

4

2 回答 2

0

您可以加入 4 个表并打开聚合。在雪花中,listagg()可用于聚合字符串:

select 
    p.product_id
    p.album_artist,
    p.album_title,
    t.track_name,
    listagg(concat(s.firstname, ' ', s.lastname, ' (', ss.ownership_share, ')') 
        within group (order by ss.ownership_share) ownership_share
from product p
inner join track t on t.product_id = p.product_id
inner join song_songwriter ss on ss.track_id = p.track_id
inner join songwriter s on s.songwriter_id = ss.songwriter_id
group by
    p.product_id
    p.album_artist,
    p.album_title,
    t.track_name
order by p.product_id, t.sequence;
于 2019-11-21T20:51:33.137 回答
0

连接字符串时,Snowflake 不使用“+”符号。您应该利用 concat() 函数或 || 符号:

https://docs.snowflake.net/manuals/sql-reference/functions/concat.html

于 2019-11-21T20:53:07.037 回答