我有一句SQL句子:
$offset = ($currentpage - 1) * $entriesPerPage;
if ($currentpage > 1) {
?where comes this variable
它产生了这个结果:
我想添加给定包的列平均排名和列数出现,这将计算包在列表中出现的数量。我也想按package_name对结果进行分组,这样我就没有裁员。
到目前为止,我已尝试在ORDER BY:
之前添加GROUP BY By子句SELECT application.id,title,url,company.name AS company_name,package_name,ranking,date,platform,country.name AS country_name,collection.name AS collection_name,category.name AS category_name FROM application
JOIN application_history ON application_history.application_id = application.id
JOIN company ON application.company_id = company.id
JOIN country ON application_history.country_id = country.id
JOIN collection ON application_history.collection_id = collection.id
JOIN category ON application_history.category_id = category.id
WHERE application.platform=0
AND country.name ='CZ'
AND collection.name='topfreeapplications'
AND category.name='UTILITIES'
AND application_history.ranking <= 10
AND date::date BETWEEN date (CURRENT_DATE - INTERVAL '1 month') AND CURRENT_DATE
ORDER BY application_history.ranking ASC
但它给我一个错误:
GROUP BY package_name
如果我添加它要求我的每一列,它就不起作用。 我还尝试通过在SELECT:
之后添加来计算包名的数量column "application.id" must appear in the GROUP BY clause or be used in an aggregate function
它会产生类似的错误。
我怎样才能得到我想要的结果?我应该改为提出两个问题,还是可以一次性获取所有内容? 我确切地说,我已经查看了S.O的其他答案,但是他们都没有尝试在“生产”栏上制作COUNT。
感谢您的帮助。
修改:
这是我最初预期的结果:
虽然戈登的建议没有给我正确的结果,但它让我走上了良好的轨道,当我读到这个: 从docs:“与常规聚合函数不同,使用窗口函数不会导致行分组为单个输出行。”
所以我回来单独使用COUNT和AVG。我的问题是我想显示排名列和日期以检查事情是否正确。但是将这些列放入Select会阻止GROUP BY按预期工作,正如Jarlh在评论中所提到的那样。
工作查询:
COUNT(package_name) AS count
答案 0 :(得分:1)
我认为您需要窗口/分析功能。以下添加了两列,一列用于每个包的行数,另一列用于它们的平均排名:
SELECT application.id, title, url, company.name AS company_name, package_name,
ranking, date, platform, country.name AS country_name,
collection.name AS collection_name, category.name AS category_name,
count(*) over (partition by package_name) as count,
avg(ranking) over (partition by package_name) as avg_package_ranking
FROM application . . .