一個有用的例子

來源:互聯網
上載者:User

選出每門學科成績在前2位的記錄,並按照 CourseID 和 Achievement 從高到低排序

-- 建表及插入資料
create table StuTable
(
StudentID varchar(8),
CourseID varchar(10),
Achievement int
)

insert StuTable select 71101, 1, 80
union all select 71102, 4, 86
union all select 71103, 2, 45
union all select 71104, 2, 88
union all select 71102, 1, 90
union all select 71103, 1, 78
union all select 71103, 3, 34
union all select 71104, 3, 64
union all select 71104, 1, 56
union all select 71101, 4, 75
union all select 71101, 2, 76
union all select 71102, 3, 56
union all select 71103, 4, 57
union all select 71102, 2, 85
union all select 71101, 3, 97
union all select 71104, 4, 96
---
Select *
From StuTable a
Where StudentID in (Select Top 2 StudentID From StuTable Where CourseID=a.CourseID Order by Achievement desc)
order by CourseID,Achievement desc

Select * from StuTable A
Where Not Exists(
select 1 from StuTable
Where CourseID=A.CourseID And Achievement>A.Achievement
Having Count(*)>1
)
Order by CourseID,Achievement Desc

drop table StuTable

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.