1

我也想从我的表中为我的表的每个组 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 中选择行

4

2 回答 2

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
于 2013-03-14T13:31:42.177 回答
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
于 2013-03-14T13:28:24.117 回答