现在的位置: 首页 > 综合 > 正文

SQL題目收集

2013年01月28日 ⁄ 综合 ⁄ 共 1869字 ⁄ 字号 评论关闭
題 1:

表结构如下
MyTable:
ID      quantity
1        3.3333
2         4.2222
3         1.5555
4         9.8888
5 ………

要求用SQL语句生成如下查询
ID           quantity   quantity
1             3.3333     3.3333
2             4.2222     7.5555
3             1.5555     9.0000
4             9.8888     18.8888
5 ………
提示:2日累计日产=1日累计日产+2日累计日产
3日累计日产=2日累计日产+3日累计日产

答案:

select id,quantity,(select sum(quantity)from mytable where id<=t.id) as acount from mytable t

題 2:

表A:
字段: id(主键) list
1 国内
2 国外
3 国内
4 国外
5 国外
6 国内
7 国外
8 国内
9 国内
10 国内
11 国外
能不能现实成:
字段: id list
1 国内
3 国内
6 国内
2 国外
4 国外
5 国外
反正意思就上把国内和国外区分显示, 先显示国内的在显示国外的,
然后每页分别显示3个国内和国外的

--建立测试环境
create table tb(id 
int,list varchar(10))
insert tb(id,list)
select 
'1','国内' union all
select 
'2','国外' union all
select 
'3','国内' union all
select 
'4','国外' union all
select 
'5','国外' union all
select 
'6','国内' union all
select 
'7','国外' union all
select 
'8','国内' union all
select 
'9','国内' union all
select 
'10','国内' union all
select 
'11','国外'
go

--分页定义表
CREATE TABLE tb_Page(
list varchar(
10) PRIMARY KEY, --类别名称,与tb表的list关联
Records 
int--每页显示的记录数
Orders 
int--在页中的显示顺序
INSERT tb_Page SELECT 
'国内',3,1
UNION ALL SELECT 
'国外',3,2

GO

--实现分页处理的存储过程
CREATE PROC p_PageView
@PageCurrent 
int=1 --要显示的当前页码
AS
SET NOCOUNT ON
--得到每页的记录数
DECLARE @PageSize 
int
SELECT @PageSize
=SUM(Records) FROM tb_Page
IF ISNULL(@PageSize,
0)<0 RETURN

--分页显示处理
SET @PageCurrent
=@PageCurrent*@PageSize
SET ROWCOUNT @PageCurrent
SELECT SID
=IDENTITY(int,1,1),ID
INTO # FROM(
SELECT TOP 
100 PERCENT a.ID
FROM tb a
LEFT JOIN tb_Page b ON a.list
=b.list
ORDER BY CASE WHEN b.list IS NULL THEN 
1 ELSE 0 END,--分类没有定义的显示在最后
((SELECT COUNT(
*) FROM tb
WHERE list
=a.list
AND (id
<a.id OR id=a.id AND id<=a.id))-1)
/b.Records,
b.Orders,a.ID )a
IF @PageCurrent
>@PageSize
BEGIN
SET @PageCurrent
=@PageCurrent-@PageSize
SET ROWCOUNT @PageCurrent
DELETE FROM #
END
SELECT a.
* FROM tb a,# b
WHERE a.ID
=b.ID
ORDER BY b.SID
GO

--调用
EXEC p_PageView 
1
go
--删除测试环境
drop table tb ,tb_page
drop proc p_PageView
go

/*--测试结果
id list
----------- ----------
1 国内
3 国内
6 国内
2 国外
4 国外
5 国外
*/

抱歉!评论已关闭.