标签:
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]
向表一插入数据:
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‘);
查询所插入的数据:
select * from dbo.Customers
结果如图:
再建表二([dbo].[Orders] 字段说明:orderid -- 订单id , customerid -- 消费者id):
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]
向表二插入数据:
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);
查询插入的数据:
select * from dbo.orders
结果如图:
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
结果如图:
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
结果如图:
SQL关于apply的两种形式cross apply和outer apply(转载)
标签:
原文地址:http://www.cnblogs.com/OpenCoder/p/5141707.html