我有一个以Count(*)为顺序的查询,其次是偏移量获取。当我使用不同的值作为偏移量时,它总是提供相同的结果集。
我尝试按照结果集变化的顺序排列某些列,并且效果很好。有人可以帮忙吗?
select
Id,
count(*) as "Count"
from
some_table
group by
"Id"
Order By
"Count" ASC OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY;
答案 0 :(得分:2)
这是您的查询:
select Id, count(*) as "Count"
from some_table
group by "Id"
order by "Count" asc
OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY;
问题是您有count(*)
的重复值。由于SQL表表示无序集,因此它没有默认顺序。当排序键具有相同的值时,这会带来问题。
简单的解决方案是在id
中包含order by
:
order by "Count" asc, id
这使得排序稳定,因此定义明确。
答案 1 :(得分:1)
这是我的示例
创建表
create table t (id int, name varchar(100))
插入数据的
insert into t values(1,'saravnan')
insert into t values(1,'kumar')
insert into t values(1,'Ravi')
insert into t values(1,'mohan')
insert into t values(2,'Raju')
insert into t values(2,'Vikram')
insert into t values(2,'AA')
insert into t values(2,'BB')
insert into t values(2,'CC')
insert into t values(2,'DD')
insert into t values(2,'EE')
insert into t values(3,'Raju')
insert into t values(3,'Vikram')
insert into t values(3,'AA')
insert into t values(4,'BB')
insert into t values(4,'CC')
insert into t values(4,'DD')
insert into t values(4,'EE')
选择所有数据
select *from t
id name
1 1 saravnan
2 1 kumar
3 1 Ravi
4 1 mohan
5 2 Raju
6 2 Vikram
7 2 AA
8 2 BB
9 2 CC
10 2 DD
11 2 EE
12 3 Raju
13 3 Vikram
14 3 AA
15 4 BB
16 4 CC
17 4 DD
18 4 EE
偏移量用于从表数据的开头跳过的行数。它应该是数字。 这是我的例子:
select id,count(*) from t group by id order by id offset 1 rows fetch next 3 row only
返回
id count
1 2 7
2 3 3
3 4 4
下一个用于返回数字行的提取。 您的示例的解决方案。
--offset 0 returns[enter image description here][1]
select Id,count(1) as "Count" from t group by ID Order By "Count" ASC OFFSET 0 ROWS FETCH NEXT 5 ROWS ONLY
Id Count
1 3 3
2 4 4
3 1 4
4 2 7
-- offset 1 returns
select Id,count(1) as "Count" from t group by ID Order By "Count" ASC OFFSET 1 ROWS FETCH NEXT 5 ROWS ONLY
Id Count
1 4 4
2 1 4
3 2 7