第四章 子查询(2)

use TSQLFundamentals2008;

--1返回Orders表中活动的最后一天生成的所有订单
select orderid, orderdate, custid, empid
from Sales.Orders as o1
where orderdate = 
(select MAX(o2.orderdate) from Sales.Orders as o2)

--2返回拥有订单数量最多的客户下过的所有订单
select custid, orderid, orderdate, empid
from Sales.Orders as o1
where custid=
(select top 1 o2.custid from Sales.Orders as o2 group by o2.custid order by COUNT(*) desc)

--3返回2008年5月1号(包括这一天)以后没有处理过订单的雇员
select empid, Firstname, lastname
from HR.Employees as e 
where e.empid not in
(select o.empid from Sales.Orders as o where o.orderdate>=N'20080501')

--4返回在客户表中出现过,但是在雇员表中没出现过的国家
select distinct c.country from Sales.Customers c
where not exists (select e.country from HR.Employees e where c.country = e.country)

select distinct c.country from Sales.Customers c
where c.country not in (select e.country from HR.Employees e)

--5为每个客户返回在他参与活动的最后一天下过的所有订单
select custid, orderid, orderdate, empid
from Sales.Orders o1
where o1.orderdate =
(select max(orderdate) from Sales.Orders o2
where o1.custid = o2.custid
group by o2.custid)
order by custid

--6返回在2007年下过订单,而在2008年没有下过订单的客户
select custid, companyname 
from Sales.Customers as c
where 
exists(select * from Sales.Orders o where c.custid=o.custid and year(o.orderdate)=2007)
and 
not exists(select * from Sales.Orders o where c.custid=o.custid and YEAR(o.orderdate)=2008)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值