Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2014-11-20 : 11:57:10
|
Hi,I have to over simplified to make my case, but trust me, this is just look-a-like a home work question.I want to return a list of students whose grades are B or better.Here is my sample. And notice neither of my Select give me the right answer. Thanks!if object_ID('tempdb..#dummySTU') is not null drop table #dummySTU;if object_ID('tempdb..#dummyGrade') is not null drop table #dummyGrade;create table #dummySTU (name char(10), ID int)insert into #dummySTUSelect 'John',11 unionSelect 'Jane',22 unionSelect 'Jim',33 create table #dummyGrade (ID int, course char(10), grade char(10))insert into #dummyGradeSelect 11,'Eng','A' unionSelect 11,'Hist','B' unionSelect 11,'Math','C' unionSelect 22,'Eng','A' unionSelect 22,'Hist','B' unionSelect 22,'Math','A' unionSelect 33,'Eng','B' unionSelect 33,'Hist','B' unionSelect 33,'Math','A' Select * from #dummySTUSelect * from #dummyGradeSelect a.id, a.name, b.grade from #dummySTU a join #dummyGrade b on a.id = b.idwhere b.grade in ('A','B')Select sum(a.id), sum(a.name), b.grade from #dummySTU a join #dummyGrade b on a.id = b.idgroup by b.gradehaving b.grade in ('A','B') --max(), sum() wouldn't workdrop table #dummySTUdrop table #dummyGrade |
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-11-20 : 12:09:28
|
This query works:Select a.id, a.name, b.grade from #dummySTU a join #dummyGrade b on a.id = b.idwhere b.grade in ('A','B') What should the output of the next query look like? |
|
|
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2014-11-20 : 13:00:10
|
returns Jane and Jim (22 and 33) but not John (11) because he has a C in math. |
|
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-11-20 : 13:04:23
|
That's what the first query does (correctly).In general, Having should only be used for aggregated columns, since their values is not known before the GROUP BY Clause. |
|
|
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2014-11-20 : 13:18:50
|
no, that has John in there because he also has A and B.Will be something like next, but it did get any for now.select * from #dummySTUwhere not exists (Select a.id from #dummySTU a join #dummyGrade b on a.id = b.idwhere b.grade in ('C','D')) |
|
|
gbritton
Master Smack Fu Yak Hacker
2780 Posts |
Posted - 2014-11-20 : 13:27:31
|
So you want to exclude students who scored anything other than A or B. This otta do it:Select a.id, a.name, b.grade from #dummySTU a join #dummyGrade b on a.id = b.idwhere b.grade in ('A','B') AND NOT exists( SELECT 1 FROM #dummyGrade dg WHERE a.id = dg.ID AND dg.grade NOT IN ('A', 'B') ) |
|
|
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2014-11-20 : 14:46:01
|
Great, thanks! |
|
|
|
|
|
|
|