第五章 表表达式

use tsql2012;

select orderid, orderdate, custid, empid,
row_number() over(order by orderdate, orderid) as rownum
from sales.orders;

select orderid, orderdate, custid, empid, rownum
from (select orderid, orderdate, custid, empid,
row_number() over(order by orderdate, orderid) as rownum
from sales.orders) as a
where a.rownum > 10 and a.rownum <= 20;

with orderrownums as
(select orderid, orderdate, custid, empid,
row_number() over(order by orderdate, orderid) as rownum
from sales.orders)
select * from orderrownums as a
where a.rownum >10 and a.rownum <=20;

with emps as
(select e1.empid, e1.mgrid, e1.firstname, e1.lastname
from hr.employees as e1
where e1.empid = 9

union all

select e2.empid, e2.mgrid, e2.firstname, e2.lastname
from hr.employees as e2
join emps as em
on e2.empid = em.mgrid)
select * from emps;

if object_id('sales.vemporders') is not null
drop view sales.vemporders;
go

create view sales.vemporders with schemabinding
as
(select o.empid, year(o.orderdate) as orderyear, sum(od.qty) as qty
from sales.orders as o
cross apply sales.orderdetails as od
where od.orderid = o.orderid
group by o.empid, year(o.orderdate));

select * from sales.vemporders order by empid, orderyear;

select v1.empid, v1.orderyear, v1.qty,
(select sum(v2.qty)
from sales.vemporders as v2
where v2.orderyear <= v1.orderyear
and v1.empid = v2.empid) as runqty
from sales.vemporders as v1
order by v1.empid, orderyear ;

if object_id('fn_Topproducts') is not null
drop function fn_Topproducts;
go
create function fn_topproducts
(@supid as int, @n as int)
returns table
as
return
(select top(@n) productid, productname, unitprice
from production.products as p
where supplierid = @supid);
go

select * from fn_topproducts(5,2);

select s.supplierid, s.companyname, f.productid, f.productname, f.unitprice
from production.suppliers as s
cross apply fn_topproducts(s.supplierid, 2) as f;

你可能感兴趣的:(表达式)