It’s possible that this question has already been asked, but I can’t seem to find my answer, so here goes:
I’m selecting 10 fields from a JOIN on two tables. The result is about 1186 rows of data. In these rows, several are duplicates for all intents and purposes, except for one unique field (ClassId). I need this field, but it’s keeping me from getting and what I have defined as “Unique”. For example, querying on only Code, TeacherDescrip, and Term yields 1120 records.
I was hoping to run this same query, but add a WHERE clause with a subquery that searched for a narrower set of fields, the three listed above to be exact, that excluded that unique field that was causing my “duplicates”. Of course, the error I received is below:
“Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS.”
When i tried to use EXISTS in stead of ClassScedule.Code IN I still got back the full 1186.
here is my query:
SELECT DISTINCT ClassId
,Code
,Section
,Course
,Students
,ClassStart
,TeacherDescrip
,AdTeacherID
,email
,Term
,Campus
FROM ClassScedule
JOIN staff ON staff.StaffID = ClassScedule.AdTeacherID
WHERE ClassStart BETWEEN '2012-03-01' AND '2012-03-30'
AND ClassScedule.Code IN
(SELECT DISTINCT ClassScedule.Code, TeacherDescrip, Termcode
FROM ClassScedule
WHERE ClassStart BETWEEN '2012-03-01' AND '2012-03-30')
AND TeacherDescrip IS NOT NULL
ORDER BY Instructor
If you are using SQL Server 2005 or later, you can select one result for each distinct (Code, TeacherDescrip, Term) as follows:
Among duplicate (Code, TeacherDescrip, Term) values, this query gives you the result with the smallest ClassID. If you want the largest instead, remove DESC.