USE [MVP]
GO
/****** 对象: Table [dbo].[t] 脚本日期: 04/14/2010 11:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[t](
[id] [int] NOT NULL,
[cate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[price] [int] NULL,
[des] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK_t] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** 对象: Table [dbo].[t] 脚本日期: 04/14/2010 11:22:16 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[t](
[id] [int] NOT NULL,
[cate] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
[price] [int] NULL,
[des] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK_t] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
题目一、取出 A类中price最大的记录
select cate,max(price) from t group by cate
如果要用分组,只能取出两列,要把所有的列都显示出来
后来想到用over
select id,des,price from
(
select *,max(price) over(PARTITION by cate) as newprice from t
) a where a.price=a.newprice
注意:Over 不能单独使用,
要和分析函数:rank(),dense_rank(),row_number()等一起使用
题目二:把这个表按每页3条记录分页
select *,row_number() over(order by price) as sort from t
declare @PageCount int
declare @RecordCount int
SELECT @RecordCount=count(id) from t
print @RecordCount
set @PageCount =CEILING ((@RecordCount+0.0)/ 3 )方法一:
select * from t
SELECT TOP 3 *
FROM t
WHERE id NOT IN
(
SELECT TOP 3 id FROM t ORDER BY id
)
ORDER BY id方法二:
SELECT TOP 3 *
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM t
) A
WHERE RowNumber > 3*(2-1)有关分页 SQL 的资料很多,有的使用存储过程,有的使用游标。本人不喜欢使用游标,我觉得它耗资、效率低;使用存储过程是个不错的选择,因为存储过程是经过预编译的,执行效率高,也更灵活。先看看单条 SQL 语句的分页 SQL 吧。
方法1:
适用于 SQL Server 2000/2005SELECT TOP 页大小 *
FROM table1
WHERE id NOT IN
(
SELECT TOP 页大小*(页数-1) id FROM table1 ORDER BY id
)
ORDER BY id
方法2:
适用于 SQL Server 2000/2005SELECT TOP 页大小 *
FROM table1
WHERE id >
(
SELECT ISNULL(MAX(id),0)
FROM
(
SELECT TOP 页大小*(页数-1) id FROM table1 ORDER BY id
) A
)
ORDER BY id
方法3:
适用于 SQL Server 2005SELECT TOP 页大小 *
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1
) A
WHERE RowNumber > 页大小*(页数-1)
说明,页大小:每页的行数;页数:第几页。使用时,请把“页大小”和“页大小*(页数-1)”替换成数字。其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。通过SQL 查询分析器,显示比较:我的结论是:
分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句
分页方案一:(利用Not In和SELECT TOP分页) 效率次之,需要拼接SQL语句
分页方案三:(利用SQL的游标存储过程分页) 效率最差,但是最为通用