作者cutekid (可爱小孩子)
看板Database
标题Re: [SQL ] 同个group取出前两笔资料
时间Tue Dec 6 16:09:49 2016
假设 table 如下,要捞出同 ID 下前两笔(key 由小大到)
ID KEY
---------
123 key1
123 key2
123 key3
456 key4
456 key5
456 key6
解答:
select ID,KEY
from ( select *,row_number() over (partition by ID order by KEY) as num )
) t1
where num <= 2
※ 引述《hungwei0331 (Game)》之铭言:
: 资料库名称:sql server
: 内容/问题描述:
: 期望同个group取出前两笔
: 假设有多笔资料
: pkey1 123
: pkey2 123
: pkey3 123
: pkey4 456
: pkey5 456
: pkey6 456
: 使用group by 後想要只取出前两笔资料如下
: pkey1 123
: pkey2 123
: pkey4 456
: pkey5 456
: 目前使用过子查询并且将连结中范例改为select top 2
: 连结如下,
: https://goo.gl/DVLvjw
: 但会有错误讯息提示子查询不可回传多笔资料
: 还请前辈们开示与提点 谢谢
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 210.61.233.210
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Database/M.1481011791.A.816.html
1F:推 streetbad: 非原PO~但感谢分享~小弟的写法习惯是拆开丢暂存.... 12/06 17:55