這是sc的表

試了幾種方法但是想不通其中一種也就是下面代碼,明明有一個統計cno的個數為2的條件限制為什么最后還會出現95001的學號,95001明明選了3節課
use School
select Sno
from SC
where Cno in ('1','3')
group by Sno
having COUNT(Cno)=2
這是結果
uj5u.com熱心網友回復:
select Sno
from SC a
where Cno in('1','3')
and not exists(select 1 from SC b where b.Sno=a.Sno and b.Cno not in('1','3'))
group by Sno
having count(1)=2
uj5u.com熱心網友回復:
Create table #SC(
Sno varchar(255),
Cno varchar(255),
Grade decimal(4,1)
)
insert into #SC
select '95001','1',92
union all
select '95001','2',85
union all
select '95001','3',88
union all
select '95002','1',90
union all
select '95003','1',82
union all
select '95003','3',85
select Sno from #SC where exists(select 1 from #SC a where a.Sno=#SC.Sno and a.Cno='3')
and not exists(select 1 from #SC b where b.Sno=#SC.Sno and b.Cno not in('1','3'))
and Cno='1'
drop table #SC
uj5u.com熱心網友回復:
你用了where ,第一步就把非 1,3 的選課記錄給過濾了,再做group by, 當然 95001 count(*) 的值為 2 ,滿足條件。have a try like this:
select sno
from #SC
group by sno
having sum(case when cno in (1,3) then 1 else 2 end) = 2
uj5u.com熱心網友回復:
最后還會出現95001的學號,95001明明選了3節課 ,因為 Cno in ('1','3') 把2的記錄過濾掉了,不就剩下2節課了嗎uj5u.com熱心網友回復:
Create table #SC
(
Sno varchar(255),
Cno varchar(255),
Grade decimal(4,1)
)
insert into #SC
select '95001','1',92
union all
select '95001','2',85
union all
select '95001','3',88
union all
select '95002','1',90
union all
select '95003','1',82
union all
select '95003','3',85
select Sno
from #SC a
where exists (select Sno,count(cno) from #SC b where a.Sno = b.sno group by sno having count(cno)=2 )
group by Sno
uj5u.com熱心網友回復:
having COUNT(Cno)=2的意思,是Cno重復出現的次數為2;而不是同一人所修課程個數。讀圖可知1出現了3次,2出現了1次,3出現了2次。
即操作物件為
-----
95001 3 88
95003 3 85
-----
如何獲取所修課程個數為2,其他樓提供了很多思路了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/22756.html
標籤:應用實例
上一篇:大資料存盤技識訓礎
下一篇:求助:產品和毛坯資料匹配查詢問題
