嗨,我有一个表Student,数据是按行插入的,我想只选择那些在所有科目中分数超过50%的学生,如果在任何科目中分数低于50%,那么它不应该在输出中选择该学生,所有记录都应该排除该学生,并且没有主键
我试过下面的代码:
Select * into #temp1 from Student where percent >=0.5 and group by Roll_Number
i am getting error:
在选择列表中无效,因为它既不包含在聚合函数中也不包含在GROUP BY子句中。
和
Select * into #temp1 from Student where percent >=0.5
然后我得到的学生谁甚至在一个科目超过50%,这是不需要在输出
表结构如下
Student_Name Roll_Number Subject Marks Percent
Ashutosh 1234 English 40 40%
Ishan 1231 Maths 60 60%
Atul 1232 Maths 30 30%
Ashutosh 1234 MAths 70 70%
现在在输出中应该只给出
Ishan 1234 Maths 60 60%
您可以使用count() over()
来指示每个学生是否有任何一行有<50%,然后使用这个作为过滤条件:
with s as (
select *,
Count(case when perc<0.5 then 1 end) over(partition by Student_Name) pc
from Students
)
select *
from s
where Percent>=0.5 and pc=0
您可以通过使用子查询/cte和窗口函数来获得所需的结果,以检查学生是否在所有科目中至少有50%:
DECLARE @Student TABLE(
Student_Name VARCHAR(20)
,Roll_Number int
,Subject VARCHAR(20)
,Marks int
,Perc DECIMAL(5,2)
)
INSERT INTO @Student VALUES
('Ashutosh',1234,'English',40,0.4)
,('Ishan',1231,'Maths',60,0.6)
,('Atul',1232,'Maths',30,0.3)
,('Ashutosh',1234,'Maths',70,0.7);
WITH cteFilter AS(
SELECT *, ROW_NUMBER() OVER (PARTITION BY Student_Name, Roll_Number ORDER BY Perc ASC, Marks ASC) rn
FROM @Student
)
SELECT *
FROM cteFilter
WHERE rn = 1
AND Perc >= 0.5