一道sql题引发的关于where、having、group by、order by 的思考

上原题:

我的语句:

CREATE TRIGGER t on SC FOR INSERT AS  DELETE FROM SC WHERE EXISTS(
SELECT * FROM inserted WHERE sno = SC.sno and cno = Sc.cno
AND sno IN (SELECT sno  FROM SC WHERE grade <60) 
AND sno IN (SELECT sno FROM SC WHERE cno IN (SELECT cno FROM Course WHERE Credit > 4) GROUP BY sno HAVING count(*) > 4)
AND sno not IN (SELECT top(0.1*(SELECT count(*) FROM Stu)  sno FROM SC GROUP BY sno ORDER BY AVG(Grade) DESC)
)

总结反思:

  • where 可以和 having 并用;where 用来筛选元组,筛选之后的元组才会用于 Group By;Having 作用于分组完成后的结果,其中可以有聚集函数,聚集函数不必出现在Select中
  • exists 是看能不能根据元组中的信息从表中匹配出结果,个人认为exists作用于每个元组,把匹配结果不为空的元组选出来
  • top 后面可以跟数量,如果想要百分比的数据,可以用百分比去乘以总数来得到想要的数量
  • Order By 后面也可跟聚集函数,聚集函数不必出现在Select 中
  • Having 用聚集函数进行筛选,Order By根据聚集函数进行排序

你可能感兴趣的:(一道sql题引发的关于where、having、group by、order by 的思考)