如何从同一个表中的每个组id中选择前n行

时间:2013-03-14 13:15:31

标签: sql sql-server-2008

我也会从我的表中为每个组ID选择前5行 我的桌子是

CREATE TABLE [dbo].[news](
    [pk_news] [int] IDENTITY(1,1) NOT NULL,
    [text] [text] NULL,
    [title] [nvarchar](500) NULL,
    [pk_service] [int] NULL,
    [image] [nvarchar](500) NULL,
    [pk_annalist] [int] NULL,
    [pk_user] [int] NULL,
    [pk_admin] [int] NULL,
    [accept] [int] NULL,
    [views] [int] NULL,
    [tag] [nvarchar](500) NULL,
    [news_Date] [date] NULL,
    [summary] [nvarchar](500) NULL,

我想从每个pk_service中选择行

2 个答案:

答案 0 :(得分:2)

首先,您必须指定在“前5名”中意味着什么?这是通过视图数量?,最新news_date?,什么?假设它是按观察次数,那么:

首先,你需要一个表达式,为每一行计算同一个pk_select中有多少个视图值大于当前记录值的记录。

假设n是当前行的别名,那将是

    Select Count(*) From news 
    Where pk_select = n.pk_Select
        And views >= n.views

然后将其作为外部查询的Where子句中的子选择嵌入

 Select * From news n
 Where (Select Count(*) From news 
        Where pk_select = n.pk_Select
           And views >= n.views) < 5

仅当视图的值不包含每个pk_Select组中的重复项时,才会生成绝对正确的答案。如果有重复项,则需要使用row_number函数

   With Rows As
   (
          Select *, 
          Row_Number() Over (Order By Views) as rowNum
          From news
   )
   Select * From Rows
   Where RowNum <= 5

答案 1 :(得分:2)

select 
    x.*
    ,n.*
from dbo.news n
join (
    select 
        pk_news
        ,[rwn] = row_number() over(partition by pk_service order by pk_news asc)
    from dbo.news
) x
on n.pk_news=x.pk_news and x.rwn < 6
order by 
    n.pk_service, x.rwn