我想在一个查询中返回每个部分的前10条记录。有人能帮我做吗?Section是表中的列之一。
数据库为SQL Server 2005。我想按输入的日期返回前10名。部分包括业务、本地和特性。对于一个特定的日期,我只想要顶部(10)业务行(最近的条目)、顶部(10)本地行和顶部(10)特性。
我想在一个查询中返回每个部分的前10条记录。有人能帮我做吗?Section是表中的列之一。
数据库为SQL Server 2005。我想按输入的日期返回前10名。部分包括业务、本地和特性。对于一个特定的日期,我只想要顶部(10)业务行(最近的条目)、顶部(10)本地行和顶部(10)特性。
当前回答
虽然这个问题是关于SQL Server 2005的,但大多数人已经继续前进了,如果他们确实发现了这个问题,在其他情况下首选的答案可能是使用CROSS APPLY,就像这篇博客文章中所说明的那样。
SELECT *
FROM t
CROSS APPLY (
SELECT TOP 10 u.*
FROM u
WHERE u.t_id = t.t_id
ORDER BY u.something DESC
) u
该查询涉及两个表。OP的查询只涉及1个表,在这种情况下,基于窗口函数的解决方案可能更有效。
其他回答
如果你知道这些部分是什么,你可以这样做:
select top 10 * from table where section=1
union
select top 10 * from table where section=2
union
select top 10 * from table where section=3
如果你想生成按节分组的输出,只显示每个节的前n条记录,如下所示:
SECTION SUBSECTION
deer American Elk/Wapiti
deer Chinese Water Deer
dog Cocker Spaniel
dog German Shephard
horse Appaloosa
horse Morgan
...那么下面的代码应该适用于所有SQL数据库。如果您想要前10,只需在查询的末尾将2更改为10。
select
x1.section
, x1.subsection
from example x1
where
(
select count(*)
from example x2
where x2.section = x1.section
and x2.subsection <= x1.subsection
) <= 2
order by section, subsection;
设置:
create table example ( id int, section varchar(25), subsection varchar(25) );
insert into example select 0, 'dog', 'Labrador Retriever';
insert into example select 1, 'deer', 'Whitetail';
insert into example select 2, 'horse', 'Morgan';
insert into example select 3, 'horse', 'Tarpan';
insert into example select 4, 'deer', 'Row';
insert into example select 5, 'horse', 'Appaloosa';
insert into example select 6, 'dog', 'German Shephard';
insert into example select 7, 'horse', 'Thoroughbred';
insert into example select 8, 'dog', 'Mutt';
insert into example select 9, 'horse', 'Welara Pony';
insert into example select 10, 'dog', 'Cocker Spaniel';
insert into example select 11, 'deer', 'American Elk/Wapiti';
insert into example select 12, 'horse', 'Shetland Pony';
insert into example select 13, 'deer', 'Chinese Water Deer';
insert into example select 14, 'deer', 'Fallow';
虽然这个问题是关于SQL Server 2005的,但大多数人已经继续前进了,如果他们确实发现了这个问题,在其他情况下首选的答案可能是使用CROSS APPLY,就像这篇博客文章中所说明的那样。
SELECT *
FROM t
CROSS APPLY (
SELECT TOP 10 u.*
FROM u
WHERE u.t_id = t.t_id
ORDER BY u.something DESC
) u
该查询涉及两个表。OP的查询只涉及1个表,在这种情况下,基于窗口函数的解决方案可能更有效。
UNION操作符对您有用吗?每个部分有一个SELECT,然后将它们联合在一起。不过,我猜它只适用于固定数量的部分。
尝试了下面的方法,它也适用于领带。
SELECT rs.Field1,rs.Field2
FROM (
SELECT Field1,Field2, ROW_NUMBER()
OVER (Partition BY Section
ORDER BY RankCriteria DESC ) AS Rank
FROM table
) rs WHERE Rank <= 10