我正在尝试建立评级系统。我正在使用visual studio。该数据库有2个表,一个表用于所有音乐曲目,另一个表包含评级,并与FK连接。
这是我的表格和专栏 http://i.gyazo.com/fc5d042749c8c04fb2b9aa2b64831b0a.png
这是我目前的尝试,它给了我一个错误
SELECT DISTINCT Track.TrackId, SUM(Ratings.rating) AS average, Track.Name, Ratings.trackid
FROM Track
INNER JOIN Ratings
ON Track.TrackId = Ratings.trackid
Msg 8120,Level 16,State 1,Line 1 列'Track.TrackId'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
答案 0 :(得分:1)
每次使用sum, avr, min or max, etc.
函数时,您必须使用Group by the law ..
首先需要做的是按轨道评分,然后将这些评分加入跟踪表,如下所示:
SELECT T.TrackId, SUM(R.rating) AS average, T.Name
FROM Track T
INNER JOIN
(SELECT TrackId, SUM(Ratings.rating) AS average
FROM Ratings Group By TrackId ) R
ON T.TrackId = r.TrackId
答案 1 :(得分:0)
如果您想使用聚合函数,那么您通常需要group by
。如果没有group by
,查询将只返回一行。
SELECT t.TrackId, SUM(r.rating) AS average, t.Name
FROM Track t INNER JOIN
Ratings r
ON t.TrackId = r.trackid
GROUP BY t.TrackId, t.name;
此外,我做了以下更改:
distinct
移除了select
。聚合查询几乎不需要这样做。Ratings.TrackId
语句中删除了select
。这是多余的,因为它与Track.TrackId
相同。group by
声明。答案 2 :(得分:0)
请勿使用distinct
。它与Group By
的功能不同。
在SQL-think中,您要做的是按Trackid对所有行进行分组,并将每个组中的评分平均为:
SELECT Track.TrackId, AVG(1.0000 * Ratings.rating) AS average
FROM Track
JOIN Ratings ON Track.TrackId = Ratings.trackid
Group By Track.TrackId
但是,你也试图同时拿起这个名字。与group by同时执行此操作在SQL中并不像您希望的那样简单。 “正确”的方式是:
SELECT
Track.TrackId,
Average,
Name
FROM Track
INNER JOIN (
SELECT TrackId, AVG(1.0000 * Ratings.rating) AS average
FROM Ratings
Group By TrackId
) R
ON Track.TrackId = R.trackid