1

我正在努力在雪花模式中创建一个语句。我需要显示所有产品和相关曲目的列表,但还需要计算每个曲目附有多少词曲作者。我的桌子是:

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

我尝试了以下操作,但是由于 group by 子句而出错。有没有人有什么建议?

SELECT prod.*, tra.TRACK_NAME,count(*) AS "Number of Songwriters"
FROM PRODUCT prod
INNER JOIN TRACK tra
ON tra.PRODUCT_ID=prod.PRODUCT_ID
INNER JOIN SONG_SONGWRITER ssw
ON ssw.TRACK_ID = tra.TRACK_ID
GROUP BY prod.PRODUCT_ID
4

2 回答 2

2

您将需要进行子选择以获取此信息。更像这样的东西:

SELECT prod.*, tra.TRACK_NAME, ssw.songwriters_count as "Number of Songwriters"
FROM PRODUCT prod
INNER JOIN TRACK tra
   ON tra.PRODUCT_ID=prod.PRODUCT_ID
INNER JOIN (
     SELECT TRACK_ID, COUNT(*) as songwriters_count
     FROM SONG_SONGWRITER
     GROUP BY TRACK_ID
  ) ssw
  ON ssw.TRACK_ID = tra.TRACK_ID;
于 2019-11-21T16:43:26.940 回答
0

您应该在 GROUP BY 子句中提及您在 SELECT 子句中提到的列:

SELECT prod.*, tra.TRACK_NAME,count(*) AS "Number of Songwriters"
FROM PRODUCT prod
INNER JOIN TRACK tra
ON tra.PRODUCT_ID=prod.PRODUCT_ID
INNER JOIN SONG_SONGWRITER ssw
ON ssw.TRACK_ID = tra.TRACK_ID
GROUP BY prod.PRODUCT_ID,prod.ALBUM_ARTIST,prod.ALBUM_TITLE
,tra.TRACK_NAME
于 2019-11-21T16:37:01.873 回答