SQL查询从同一列同一表中排除某个值?

时间:2017-03-07 00:33:50

标签: sql sql-server

假设我有一个名为ACADEMICDETAIL的学生表,它看起来像这样:( ADW代表添加/删除等待,可以将这些值'A'=添加,'D'=删除,'W'=等待)

PeopleID  |  ADW  | Class  | Term  |  Year
  1234        A      Math   Spring    2017
  1234        D     Spanish Spring    2017
  1234        A      Biol    Fall     2016
  1234        A      Engl    Fall     2016
  0001        D      Engl   Spring    2017
  0001        D      Math   Spring    2017
  0001        D      Biol   Spring    2017
  5601        W      Math   Spring    2017
  2300        D      Biol   Spring    2017
  2300        A      Engl    Fall     2016

我的(坏)查询看起来像这样:

SELECT distinct PeopleId 
FROM ACADEMICDETAIL
WHERE 
Term = 'Spring' and 
Year = '2017' and
ADW = 'D'

我只需要拔掉那些特定年/学期的所有课程的学生。如果有些人被删除但其他人仍然被添加,我不需要这些学生。

所以我需要得到的结果:

 PeopleID
   0001 
   2300

我的错误查询的现实:

 PeopleID
   0001 
   2300
   1234

任何提示?我不希望1234学生出现,因为该学生既有增加也有下降。

6 个答案:

答案 0 :(得分:1)

思考SC_CLOSEgroup by

having

这会选择所有SELECT year, term PeopleId FROM ACADEMICDETAIL GROUP BY year, term, PeopleId HAVING MIN(ADW) = 'D' and MAX(ADW) = 'D'; /年term WHERE`子句,以限制只有一个或几个。

答案 1 :(得分:0)

嗨,我认为你得到的结果是正确的。根据您的查询,实际上有3个不同的行符合您的条件。

答案 2 :(得分:0)

如果该特定ID存在任何其他AWD,您需要检查每个PeopleID。

SELECT distinct PeopleId 
FROM ACADEMICDETAIL AS A 
WHERE 
Term = 'Spring' and  Year = '2017' and
((Select count (*) from ACADEMICDETAIL as A1 where AWD = 'D' and A1.PeopleID = A.PeopleID) - 
(Select count (*) from ACADEMICDETAIL as A2 where AWD = 'A' and A2.PeopleID = A.PeopleID) ) >= 0 

EDIT1:

我创建表,插入数据并运行查询。 您可以看到结果HERE

答案 3 :(得分:0)

enter image description here

如果您区分数据。你会得到3个不同的价值。简而言之,您的脚本和结果是正确的

答案 4 :(得分:0)

我认为这就是你要找的东西。

SELECT DISTINCT PeopleID
FROM ACADEMICDETAIL 
WHERE ADW = 'D' 
AND Term = 'Spring'
AND Year = '2017'
AND Peopleid NOT IN (SELECT DISTINCT PeopleId 
FROM ACADEMICDETAIL
WHERE Term = 'Spring'
AND Year = '2017'
AND ADW IN ('A' , 'W'))

答案 5 :(得分:0)

尝试下面的解决方案

-- to display 2017 Drop only select distinct PeopleID from ACADEMICDETAIL t1 where adw = 'D' and year = 2017 and not exists (select 1 from ACADEMICDETAIL t2 where t1.year = t2.year and t1.adw <> t2.ADW and t1.PeopleID = t2.PeopleID)

-- to display all Drop years select distinct PeopleID,Year from ACADEMICDETAIL t1 where adw = 'D' and not exists (select 1 from ACADEMICDETAIL t2 where t1.year = t2.year and t1.adw <> t2.ADW and t1.PeopleID = t2.PeopleID)