我正在努力在雪花模式中创建一条语句。我需要显示所有产品和相关曲目的列表,但还需要在每行上包括歌曲作者姓名和所有权百分比的列表。添加一个看起来像这样的列:“ 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_ARTIST | ALBUM_TITLE | TRACK_NAME |所有权
1 |肉饼|蝙蝠走出地狱蝙蝠走出地狱肉糕(50%),约翰尼(Johnny)词曲作者(50%
有人可以帮忙吗?
答案 0 :(得分:1)
在连接字符串时,Snowflake不使用'+'表示法。您应该利用concat()函数或||表示法:
https://docs.snowflake.net/manuals/sql-reference/functions/concat.html
答案 1 :(得分: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;