Home >Database >Mysql Tutorial > sql 选取每个分组中的第一条数据

sql 选取每个分组中的第一条数据

WBOY
WBOYOriginal
2016-06-07 17:43:021713browse

--1.创建测试表 Create Table #Order1 ( OrderName varchar(50), RequestDate datetime, OrderCount int ) -- 插入测试数据 insert into #Order1 values('衣服','2013-06-02',2) insert into #Order1 values('衣服','2013-06-03',4) insert into #Order1 val

--1.创建测试表
Create Table #Order1
(
OrderName varchar(50),
RequestDate datetime,
OrderCount int
)
-- 插入测试数据
insert into #Order1 values('衣服','2013-06-02',2)
insert into #Order1 values('衣服','2013-06-03',4)
insert into #Order1 values('衣服','2013-06-04',5)

insert into #Order1 values('鞋','2013-06-02',3)
insert into #Order1 values('鞋','2013-06-03',7)
insert into #Order1 values('鞋','2013-06-04',8)

--选取每组中时间最近的一条

-- 方法1

select * from
(
select ROW_NUMBER()over(PARTITION By OrderName ORDER BY RequestDate DESC) as rownum, OrderCount,OrderName
from #Order1
) T
where T.rownum = 1

--group by OrderName
drop table #Order1

--未完待续

,香港空间,网站空间,香港服务器租用
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article: 【转】SQL行列转换Next article: 第四章 高级查询