得到每组前几条数据

--得到每组前几条数据
--假設每組Col1中, Col3不會重復

--建立測試環境
Create Table TEST
(Col1 Varchar(10),
 Col2 Varchar(10),
 Col3 Int)
--插入數據
Insert TEST Select 'BD1V','Label', 4
Union All Select 'BD1V', 'BATT', 2
Union All Select 'BD1V', 'ODD', 3
Union All Select 'BD1V', 'HDD', 5
Union All Select 'BD1V', 'LCD', 1
Union All Select 'BD1W','HDD', 3
Union All Select 'BD1W','RAM', 8
Union All Select 'BD1W','TP CABLE', 5
Union All Select 'BD1W','LCD', 6
Union All Select 'BD1W','Label', 2
Union All Select 'BL3', 'LCD CABLE', 7
Union All Select 'BL3', 'LABEL', 6
Union All Select 'BL3', 'LCD', 5
Union All Select 'BL3', 'RAM', 1
Union All Select 'BL3D', 'Label', 4
GO
--測試
--方法一:
Select Col1, Col2, Col3 From TEST A
Where (Select Count(*) From TEST Where Col1 = A.Col1 And Col3 > A.Col3) < 3
Order By Col1, Col3 Desc
--方法二:
Select Col1, Col2, Col3 From TEST A
Where Exists (Select Count(*) From TEST Where Col1 = A.Col1 And Col3 > A.Col3 Having Count(*) < 3)
Order By Col1, Col3 Desc
--方法三:
Select Col1, Col2, Col3 From TEST A
Where Col3 In (Select TOP 3 Col3 From TEST Where Col1 = A.Col1 Order By Col3 Desc)
Order By Col1, Col3 Desc
GO
--刪除測試環境
Drop Table TEST
--結果
/*
Col1  Col2   Col3
BD1V HDD  5
BD1V Label  4
BD1V ODD  3
BD1W RAM  8
BD1W LCD   6
BD1W TP CABLE 5
BL3  LCD CABLE 7
BL3  LABEL  6
BL3  LCD   5
BL3D Label  4
*/

阅读更多
文章标签: table insert go
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

得到每组前几条数据

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭