我正在处理一个歌曲存档数据库,而我却陷入了一些疑问。我想 -
Comments
的平均值score
计算每个用户的评分,并将评分插入Users
score
表Song
的平均Comments
credits
次下面你可以找到我的桌子......
CREATE TABLE Users
(
username NVARCHAR( 30 ) NOT NULL PRIMARY KEY,
pass NVARCHAR( 16 ),
email NVARCHAR( 50 ),
city NVARCHAR( 10 ),
credits INT,
rating INT
)
CREATE TABLE Songs
(
song_id INT NOT NULL IDENTITY ( 1, 1 ) PRIMARY KEY,
song_name NVARCHAR( 30 ),
username NVARCHAR( 30 ),
genre INT,
price INT,
song_length INT,
listens INT
)
CREATE TABLE Genres
(
genre_id INT NOT NULL IDENTITY ( 1, 1 ) PRIMARY KEY,
genre_name NVARCHAR( 16 )
)
CREATE TABLE Purchases
(
purchase_id INT NOT NULL IDENTITY ( 1, 1 ) PRIMARY KEY,
song_id INT,
username NVARCHAR( 30 )
date_purchased DATETIME
)
CREATE TABLE Comments
(
comment_id INT NOT NULL IDENTITY ( 1, 1 ) PRIMARY KEY,
username NVARCHAR( 30 ),
song_id INT,
text NVARCHAR( 30 ),
score INT
)
答案 0 :(得分:0)
我回答了你的一些问题。除了相应的查询之外,我还将它们排列为常用的表表达式,我认为这可能是一种使用它们的便捷方式......
计算每个用户在购买时花费的信用额度,可能需要了解用户如何投资其信用的逻辑。
WITH CTE_PurchasesByUser AS
(
SELECT p.username as username, count(*) as NrOfPurchases
FROM Purchases p
GROUP BY p.username
),
CTE_AverageScoreBySong AS
(
SELECT c.song_id as song_id, (sum(c.score)/count(c.score)) as AverageScore
FROM Comments c
GROUP BY c.song_id
),
CTE_AverageScoreByUser AS
(
SELECT u.username as username, (sum(c.score)/count(c.score)) as AverageScore
FROM Users u
INNER JOIN Comments c ON u.username = c.username
GROUP BY u.username
)
SELECT u.*, ISNULL(bbu.NrOfPurchases,0), asu.AverageScore
FROM Users u
LEFT JOIN CTE_PurchasesByUser bbu ON u.username = bbu.username
LEFT JOIN CTE_AverageScoreByUser asu ON u.username = asu.username
这个SQL与您的表一起运行,但我没有用数据行测试它......