[英]SQL - Create view with SUM of the first N row of an ordered group
I've this table in my MYSQL db, and I want to create a view as the title. 我在MYSQL数据库中有此表,我想创建一个视图作为标题。 Table:
表:
ID | Result
---+-------
1 | 10
3 | 7
1 | 4
2 | 5
1 | 3
The view should select group by ID, SUM(result), and consider only the best 2 results for each ID, and order everything by the result. 该视图应按ID,SUM(result)选择分组,并仅考虑每个ID的最佳2个结果,并按结果对所有结果进行排序。 So.. View:
所以..查看:
ID | Result
---+--------
1 | 14
3 | 7
2 | 5
I tried with: 我尝试过:
CREATE OR REPLACE VIEW final_res AS
SELECT `ID` , SUM( `result` )
FROM `result_table`
GROUP BY `ID`
HAVING COUNT(*)<=2
ORDER BY `result`
But this doesn't work. 但这是行不通的。 :/
:/
One option is to create a row number using user-defined variables
within each group ordered by the result desc
, and then limit the sum
to the first 2 rows within each group: 一种选择是使用
user-defined variables
在由result desc
排序的每个组中创建一个行号,然后将sum
限制为每个组中的前2行:
select id, sum(result)
from (
select id, result, @rn:=if(@prevId=ID,@rn+1,1) rn, @prevId:=id
from result_table join (select @rn:=0, @previd:=0) t
order by id, result desc
) t
where rn <= 2
group by id
order by 2 desc
Alternatively, you could use a correlated subquery, but I think the row number approach is a bit cleaner: 另外,您可以使用相关的子查询,但是我认为行号方法更为简洁:
select t.id, max(t.result) + coalesce((
select max(t2.result)
from result_table t2
where t.id = t2.id and t.result != t2.result
),0)
from result_table t
group by id
order by 2 desc
You're not going to get anything because you're grouping on ID, your HAVING clause is saying where there's more than one ID. 您将无法获得任何信息,因为您正在对ID进行分组,而HAVING子句是在说明不止一个ID。 This will never happen
这永远不会发生
CREATE OR REPLACE VIEW final_res AS
SELECT TOP 2 `ID` , SUM( `result` )
FROM `result_table`
GROUP BY `ID`
ORDER BY `result` desc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.