use tsql2012;
--returm the max order for each customer
select custid, orderid, orderdate, empid
from sales.orders as o1
where orderid =
(select max(o2.orderid) from sales.orders as o2 where o2.custid=o1.custid);
--val percent
select orderid,custid, val, cast(100.* val/(select sum(o2.val)
from sales.ordervalues as o2
where o2.custid = o1.custid) as numeric(5,2)) as pct
from sales.ordervalues as o1
order by custid, orderid;
select custid, companyname
from sales.customers as C
where c.country = N'Spain'
and exists (select * from sales.orders as o
where o.custid = c.custid);
select custid, companyname
from sales.customers as c
where c.country = N'Spain'
and not exists (select * from sales.orders as o
where o.custid = c.custid);
select orderid, orderdate, empid, custid,
(select max(o2.orderid) from sales.orders as o2
where o2.orderid < o1.orderid)
from sales.orders as o1;
select orderid, orderdate, empid, custid,
(select min(o2.orderid) from sales.orders as o2
where o2.orderid > o1.orderid)
from sales.orders as o1;
select orderyear, qty,
(select sum(o2.qty)
from sales.ordertotalsbyyear as o2
where o2.orderyear <= o1.orderyear) as sumqty
from sales.ordertotalsbyyear as o1
order by orderyear;
select orderid, orderdate, custid, empid
from sales.orders as o1
where o1.orderdate =
(select max(o2.orderdate) from sales.orders as o2);
select custid, orderid, orderdate, empid
from sales.orders as o1
where custid in (select top(1) with ties o2.custid
from sales.orders as o2
group by o2.custid
order by count(*) desc);
select e.empid, e.firstname, e.lastname
from hr.employees as e
where not exists(
select * from
sales.orders as o
where o.empid = e.empid and o.orderdate > '20080501');
select distinct c.country
from sales.customers as c
where not exists(
select * from
hr.employees as e
where e.country = c.country);
select custid, orderid, orderdate, empid
from sales.orders as o1
where o1.orderdate =
(select max(orderdate)
from sales.orders as o2
where o1.custid = o2.custid)
order by custid;
select c.custid, c.companyname
from sales.customers as c
where exists
(select * from sales.orders as o
where o.custid = c.custid
and o.orderdate between '20070101' and '20071231')
and not exists
(select * from sales.orders as o2
where o2.custid = c.custid
and o2.orderdate between '20080101' and '20081231');
select c.custid, c.companyname
from sales.customers as c
where exists(
select * from sales.orders as o
where o.custid = c.custid
and exists(
select * from sales.orderdetails as od
where o.orderid = od.orderid and
od.productid = 12));
select c.custid, c.ordermonth, c.qty,
(select sum(c2.qty)
from sales.custorders as c2
where c2.ordermonth <= c.ordermonth
and c.custid = c2.custid)
as runqty
from sales.custorders as c
order by custid, ordermonth;