sql server 2008语言基础: 子查询习题

独立子查询

独立标量子查询

image

相关子查询

image

not in () 的null值处理.

 

--返回由拥有订单数目最多的客户下过的所有订单. 注意, 多个客户可能下过的订单数目是一样的
--因此用到了with ties子句
--select o.custid, o.orderid, o.orderdate, o.empid from Sales.Orders o where custid in
--(
--    select top 1 with ties custid from Sales.Orders group by custid order by COUNT(*) desc
--)

--返回'2008-05-01'之后就没有处理过订单的员工
--select * from HR.Employees e
--where not exists(select * from Sales.Orders o where orderdate>='2008-05-01' and o.empid=e.empid)

--返回在客户表中出现过, 但是没有在员工表中出现过的国家
--select distinct country from Sales.Customers where country not in 
--(select country from hr.Employees where country is not null)

--为每个客户返回在他参加活动的最后一天下过的所有订单.
--select * from Sales.Orders o inner join 
--(
--    select max(orderdate) dt, custid from Sales.Orders group by custid
--) t on o.custid=t.custid and o.orderdate=t.dt

--返回2007年下过订单, 但是08年没有下过订单的客户
--select * from Sales.Orders o where YEAR(orderdate)=2007
--and not exists(select custid from Sales.Orders o2 where o.custid=o2.custid and YEAR(orderdate)=2008)

--返回订购了第12号产品的客户.
--select distinct c.custid,companyname from Sales.Orders o inner join Sales.OrderDetails od on o.orderid=od.orderid
--inner join Sales.Customers c on o.custid=c.custid where od.productid=12

--计算每个客户在每个月的连续总订货量
select c.custid,c.ordermonth,c.qty,
(select SUM(qty) from Sales.CustOrders co2 where co2.ordermonth<=c.ordermonth
    and co2.custid=c.custid
) from Sales.CustOrders c order by custid

转载于:https://www.cnblogs.com/jianjialin/archive/2012/04/09/2439154.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值