Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 获取具有最大值的其他列(属性)_Sql_Database_Oracle_Group By_Greatest N Per Group - Fatal编程技术网

Sql 获取具有最大值的其他列(属性)

Sql 获取具有最大值的其他列(属性),sql,database,oracle,group-by,greatest-n-per-group,Sql,Database,Oracle,Group By,Greatest N Per Group,我的数据帧 ID COURSE_ID SEC_ID SEMESTER YEAR GRADE 00128 CS-101 1 Fall 2009 A 00128 CS-347 1 Fall 2009 A- 12345 CS-101 1 Fall 2009 C .... 我想在2009年秋季获得注册人数最多的课程id和sec id(计数(id)) 所以,我试过了 select course_id,

我的数据帧

ID      COURSE_ID SEC_ID SEMESTER YEAR  GRADE
00128   CS-101    1      Fall   2009    A
00128   CS-347    1      Fall   2009    A-
12345   CS-101    1      Fall   2009    C
....
我想在2009年秋季获得注册人数最多的课程id和sec id(计数(id))

所以,我试过了

select course_id, sec_id, enrollment
from (select course_id, sec_id, count(ID) as enrollment
    from takes
    where semester = 'Fall' and year = 2009
    group by course_id, sec_id)
然而,这将导致每个班级都有注册者。我只想显示那些注册人数最多的类。我想我需要使用max,但现在我需要用这段代码的小节from来解决它。(来自子查询)

++我能用having子句解决它吗? 如果你能告诉我,我将不胜感激


感谢阅读。

您可以对2009年秋季开始的课程进行筛选,按
课程id
秒id
进行聚合,按每组的行数对结果进行排序,并使用行限制条款获得最受关注的课程:

select course_id, sec_id, count(*) no_registrants
from takes
where semester = 'Fall' and year = '2009'
group by course_id, sec_id
order by no_registrants desc
fetch first 1 rows with ties
如果有,这样可以打领带。如果只需要一行,可以将
fetch first 1 rows with ties
更改为
fetch first 1 rows only
。您可能还想添加第二个排序条件,以使结果具有确定性(否则,它是未定义的,因为它将出现在“有联系”中)


在Oracle<12c中,如果行限制子句不可用,则可以使用
rank()
(或
row\u number()
来禁止):


根据我对您需求的理解,您的查询只需修改即可得到正确的结果

只获得一个注册人数最多的记录。使用相同的查询,只需添加以下提到的更改:

select course_id, sec_id, max(enrollment) as registrants
from (select course_id, sec_id, count(ID) as enrollment
from takes
where semester = 'Fall' and year = 2009
group by course_id, sec_id) as Rdet group by course_id,sec_id;

这将根据您的需求提供适当的结果。

您可以将子查询放在CTE中以重用它:

with
x as (
  select course_id, sec_id, count(*) as enrollment
  from takes
  where semester = 'Fall' and year = 2009
  group by course_id, sec_id
)
select *
from x
where enrollment = (select max(enrollment) from x)

帮助您变得容易:。如果两个值相同怎么办?@GordonLinoff在此数据集中,它不会重复!是的,我是使用“with”完成的,这是一个使用from子句解决的问题。这将与sql server一起使用。您正在使用哪个服务器?哪个版本?
您使用的是哪个服务器
-问题已标记。
with
x as (
  select course_id, sec_id, count(*) as enrollment
  from takes
  where semester = 'Fall' and year = 2009
  group by course_id, sec_id
)
select *
from x
where enrollment = (select max(enrollment) from x)