如何为T-SQL中IN语句中列出的每个数据提取10条数据?
以下是查询示例:
SELECT
student_id, student_name, student_phnumber
FROM
student
WHERE
student_name IN ('Rachel', 'Adam', 'Terry')
我只想要名叫雷切尔的10个人和亚当的10个人以及特里的10个人。在数据库中,有1000个具有该名称。如何在不使用union的情况下执行此操作?
这只是一个示例SQL。我正在使用的那个有数百万行
答案 0 :(得分:4)
这是一种带窗口功能的方式。
numberofLines = 0
答案 1 :(得分:3)
以下是使用Apply
运算符和Table valued constructor
SELECT tc.student_name,
oa.*
FROM (VALUES ('Rachel'),('Adam'),('Terry'))tc (student_name)
OUTER apply (SELECT TOP 10 student_id,
student_name,
student_phnumber
FROM student a
WHERE a.student_name = tc.student_name) oa
创建以下index
将有助于查询更快地运行
create nonclustered index nix_student
on student (student_name) include (student_id,student_phnumber )
答案 2 :(得分:2)
一个选项是ROW_NUMBER()
:
SELECT student_id, student_name, student_phnumber
FROM (
SELECT student_id
,student_name
,student_phnumber
, ROW_NUMBER() OVER (PARTITION BY student_name ORDER BY student_name) RN
FROM student
WHERE student_name in ( 'Rachel','Adam','Terry')
) A
WHERE RN < 11
@scsimon打败我吧......我将离开这只是为了展示写作的内联方式。
答案 3 :(得分:-1)
select * from
(
Select student_id
,student_name
,student_phnumber
,row_number() over (partition by student_name order by student_id) rn
from student
where
group by student_name
)
where student name in ( 'Rachel','Adam','Terry'))
and rn <11;