[英]Mysql Query Min And Max with Limit N Grouping
I'd like to ask some question about query. 我想问一些有关查询的问题。
This is my case: 这是我的情况:
codenumber varchar (PK)
prize varchar
batchno double
category varchar
Sample Data On Database: 数据库上的样本数据:
Code Prize BatchNumber Category
1000000231 TRY AGAIN 1 A
1000000238 TRY AGAIN 2 A
1000000376 TRY AGAIN 3 A
1000000473 TRY AGAIN 4 A
1000000934 50 5 A
1000001281 50 6 B
1000001894 50 7 B
1000002014 TRY AGAIN 8 B
1000002831 TRY AGAIN 9 B
1000003123 TRY AGAIN 10 B
1000003158 TRY AGAIN 11 C
1000003224 TRY AGAIN 12 C
1000003524 TRY AGAIN 13 C
1000003598 50 14 C
1000003616 TRY AGAIN 15 C
1000003657 TRY AGAIN 16 A
1000003959 50 17 A
1000004289 TRY AGAIN 18 A
1000004529 TRY AGAIN 19 A
1000004853 TRY AGAIN 20 A
1000005683 TRY AGAIN 21 B
1000005728 100 22 B
1000005816 TRY AGAIN 23 B
1000006325 TRY AGAIN 24 B
I wanted to get the Minimum and Maximum batch number for each 5 rows. 我想获得每5行的最小和最大批号。 Then how to get the query result like below: 然后如何获取查询结果,如下所示:
Category MinBatch MaxBatch
A 1 5
B 6 10
C 11 15
A 16 20
B 21 24
Please Help Thanks 请帮忙谢谢
Below query will give you the result 下面的查询将为您提供结果
select category, min(batchnumber)as 'MinBatch', max(batchnumber)as 'MaxBatch'
from tablename order group by (category)
Presuming that batch
represents the ordering for determining groups of 5, you can do this with variables: 假设batch
代表确定5组的顺序,则可以使用变量执行此操作:
select category, min(batch), max(batch)
from (select s.*, (@rn := @rn + 1) as rn
from structure s cross join
(select @rn := 0) params
order by batch
) s
group by floor((rn - 1) / 5)
order by min(batch);
Actually, if you know the batches are consecutive with no gaps and start at 1: 实际上,如果您知道批次是连续的且没有间隔,则从1开始:
select category, min(batch), max(batch)
from structure s
group by floor((batch - 1) / 5)
order by min(batch);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.