我需要有关下面 SQL Lite 代码的帮助。我希望找到每个粉丝数量分布组的平均值和计数。当我运行代码时,我只看到所有用户的平均值,并且该组显示为第一组 0-20 名粉丝。
谢谢!
SELECT
CASE
WHEN U.Fans >0 AND U.Fans <=20 THEN '0-20 Fans'
WHEN U.Fans >20 AND U.Fans <=40 THEN '21-40 Fans'
WHEN U.Fans >40 AND U.Fans <=60 THEN '41-60 Fans'
WHEN U.Fans >60 AND U.Fans <=80 THEN '61-80 Fans'
END AS 'Distribution of Fans',
AVG(U.Review_Count) AS Average_Review_Count,
AVG(U.Average_Stars) AS Average_of_Average_Stars,
COUNT(R.Useful = 1),
COUNT(R.Funny = 1),
COUNT(R.Cool = 1)
FROM User AS U
INNER JOIN Review AS R ON U.Id = R.User_Id
GROUP BY 'Distribution of Fans'
我尝试按“粉丝分布”进行分组,希望能够看到我在 Case/When 语句中创建的每组粉丝的平均值/计数。
您需要子查询所需的分组字段或直接在分组中使用它。不能对同一查询范围中的派生表达式进行分组,除非派生表达式也在分组依据中使用。另外,我将
COUNT(Field=1)
转换为 SUM(CASE 1 OR 0)
SELECT
CASE
WHEN U.Fans >0 AND U.Fans <=20 THEN '0-20 Fans'
WHEN U.Fans >20 AND U.Fans <=40 THEN '21-40 Fans'
WHEN U.Fans >40 AND U.Fans <=60 THEN '41-60 Fans'
WHEN U.Fans >60 AND U.Fans <=80 THEN '61-80 Fans'
END AS 'Distribution of Fans',
AVG(U.Review_Count) AS Average_Review_Count,
AVG(U.Average_Stars) AS Average_of_Average_Stars,
SUM(CASE WHEN R.Useful = 1 THEN 1 ELSE 0 END),
SUM(CASE WHEN R.Funny = 1 THEN 1 ELSE 0 END),
SUM(CASE WHEN R.Cool = 1 THEN 1 ELSE 0 END)
FROM User AS U
INNER JOIN Review AS R ON U.Id = R.User_Id
GROUP BY
CASE
WHEN U.Fans >0 AND U.Fans <=20 THEN '0-20 Fans'
WHEN U.Fans >20 AND U.Fans <=40 THEN '21-40 Fans'
WHEN U.Fans >40 AND U.Fans <=60 THEN '41-60 Fans'
WHEN U.Fans >60 AND U.Fans <=80 THEN '61-80 Fans'
END