SQL題目收集

來源:互聯網
上載者:User
題 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 國外
*/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.