CREATE TABLE [dbo].[Customers]( [customerid] [char](5) COLLATE Chinese_PRC_CI_AS NOT NULL, [city] [varchar](10) COLLATE Chinese_PRC_CI_AS NOT NULL, PRIMARY KEY CLUSTERED ( [customerid] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]
向表一插入數據:sql
insert into dbo.Customers values('FISSA','Madrid'); insert into dbo.Customers values('FRNDO','Madrid'); insert into dbo.Customers values('KRLOS','Madrid'); insert into dbo.Customers values('MRPHS','Zion');
查詢所插入的數據:express
select * from dbo.Customers
結果如圖:app
再建表二([dbo].[Orders] 字段說明:orderid -- 訂單id , customerid -- 消費者id):spa
CREATE TABLE [dbo].[Orders]( [orderid] [int] NOT NULL, [customerid] [char](5) COLLATE Chinese_PRC_CI_AS NULL, PRIMARY KEY CLUSTERED ( [orderid] ASC )WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY] ) ON [PRIMARY]
向表二插入數據:3d
insert into dbo.Orders values(1,'FRNDO'); insert into dbo.Orders values(2,'FRNDO'); insert into dbo.Orders values(3,'KRLOS'); insert into dbo.Orders values(4,'KRLOS'); insert into dbo.Orders values(5,'KRLOS'); insert into dbo.Orders values(6,'MRPHS'); insert into dbo.Orders values(7,null);
查詢插入的數據:code
select * from dbo.orders
結果如圖:blog
select * from dbo.Customers as C cross apply (select top 2 * from dbo.Orders as O where C.customerid=O.customerid order by orderid desc) as CA
結果如圖:ci
select * from dbo.Customers as C outer apply (select top 2 * from dbo.Orders as O where C.customerid=O.customerid order by orderid desc) as CA
結果如圖:it