【问题标题】:In SQL Server, how to pick top 4th row?在 SQL Server 中,如何选择前 4 行?
【发布时间】:2016-12-05 11:19:23
【问题描述】:

为每个 Id# 选择前 4 行的 SQL 查询是什么?

它不是前 4 行记录。我试图为每个 id 只选择第 4 行记录/列。

【问题讨论】:

  • 行是升序还是降序?你能举个例子说明输出应该是怎样的吗?
  • 每个 Bill Id 都有几行 Transactions。我只需要从顶部选择第 4 行。
  • 如果您使用的是 MySQL,那么有限制子句来设置偏移 n 检索的行数
  • 我正在尝试获取 SQL 2008 上的查询

标签: sql sql-server sql-server-2008 greatest-n-per-group


【解决方案1】:

使用row_number函数:

With cte as
(
    select 
        *,
        row_number() over (partition by id order by id) as rownum
    from 
        table 
)
select * 
from cte 
where rownum = 4

根据你对top的定义在分区中更改顺序

【讨论】:

    【解决方案2】:

    您可以使用以下查询并传递所需的表 ID 以获取特定的第 4 行:

    SELECT * 
    FROM 
        (SELECT 
             m.CityId, m.Country, m.Location, m.NoofDweller, 
             ROW_NUMBER() OVER (ORDER BY Country ASC) AS RowNumber 
         FROM 
             Cities m 
         WHERE 
             m.Country = 3 -- Just pass the required ID of the table 
        ) AS Details
    WHERE 
        RowNumber = 4 -- Gets details of the 4th row of the given ID 
    

    【讨论】:

      猜你喜欢
      • 2017-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 2016-05-15
      相关资源
      最近更新 更多