Sql学习第九天——SQL 关于over
Sql学习第九天——SQL 关于over
以前总是认为over是与row_number()结合使用的,今天突然发现它还可以与count()结合。现在就来看看它是怎样与over结合的吧!
还是从例子中理解它:
建表([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
结果如图:
直接上三条sql语句比较进行对比说明,这样比较明了。
sql语句一(简单的查询所有的数据):
select * from dbo.Orders
sql语句二(用到了count与over的结合):
select orderid , customerid,count(*) over(partition by customerid) as num_orders from orders
sql语句三(用到了count与over的结合并且带上了条件):
select orderid , customerid,count(*) over(partition by customerid) as num_orders from orders where customerid is not null and orderid%2 = 1
结果分析图:
看完图可能都会明白是怎么一回事儿了,对于partition by 我前面有说(查看请点次链接)。