一些常用Sql备忘

 1、sql中的all、any
All:对所有数据都满足条件,整个条件才成立,例如:5大于所有返回的id
 

select * from #A where 5>All(select id from #A)

 Any:只要有一条数据满足条件,整个条件成立,例如:3大于1,2

select * from #A where 3>any(select id from #A)

2、sql中的Having
在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用。
我们希望查找订单总金额少于 2000 的客户。

SELECT Customer,SUM(OrderPrice) FROM Orders
GROUP BY Customer
HAVING SUM(OrderPrice)<2000

3、sql中的where、order by、group by、having
执行顺序:where>group by>having>order by

 

SELECT select_list 
[INTO new_table] 
FROM table_source 
[WHERE search_condition] 
[GROUP BY group_by_expression]
[HAVING search_condition]  
[ORDER BY group_by_expression]

注:(1)having通常与group by联合使用,使用group by对结果集分组,然后通过having对每组进行过滤。
(2)group by与order by 联合使用,使用group by对结果集分组,然后通过having对每组进行分组。
(3)having 子句中的每一个元素也必须出现在select列表中。有些数据库例外,如oracle。
(4)having子句限制的是组,而不是行。where子句中不能使用聚集函数,而having子句中可以。

4、题目:如下表,用一条select语句求出所有课程(共三门)在80分(含80分)以上的学生姓名,请写出所有可行方案。(注意:表名为sc,字段为name,kc,score)
(1)分组,最小值

select name from sc group by name having min(score)>=80 and having count(distinct kc)>=3

(2)筛选,分组

select name from sc where score>=80 group by name having count(distinct kc)>=3

(3)嵌套

select distinct name from sc where name not in  (select name from sc where score<80)

(4)内连接

select distinct a.name from sc a,sc b,sc c 
 where a.name=b.name and a.name=c.name
 and a.kc<>b.kc and a.kc<>c.kc and b.kc<>c.kc
 and b.score>=80 and a.score>=80 and c.score>=80


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值