SQL读取特定行值

时间:2019-01-07 23:55:33

标签: sql sql-server

我需要使用一个查询来获取前5个值作为单行结果。我知道以下内容不起作用,但我认为这是我要实现的目标的一个很好的例子

SELECT
   idimage[0] AS Row1, //idimage row 1 value
   idimage[1] AS Row2, //idimage row 2 value
   idimage[2] AS Row3, //idimage row 3 value
   idimage[3] AS Row4, //idimage row 4 value
   idimage[4] AS Row5  //idimage row 5 value
FROM
IMAGES

有人知道实现此目标的最佳方法吗?我确信语法必须非常简单,但是我似乎找不到它。

3 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select max(case when seqnum = 1 then idimage end) as idimage1,
       max(case when seqnum = 2 then idimage end) as idimage2,
       max(case when seqnum = 3 then idimage end) as idimage3,
       max(case when seqnum = 4 then idimage end) as idimage4,
       max(case when seqnum = 5 then idimage end) as idimage5       
from (select i.*, row_number() over (order by ?) as seqnm
      from images i
     ) i;

请注意,SQL表表示无序集。 ?中的order by用于指定顺序的列。

答案 1 :(得分:0)

如果我正确理解了您想做什么,也许您可​​以通过以下方式使用一些子查询:

SELECT 
 (SELECT idimage from IMAGES ORDER BY id desc OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY ) AS ROW1, 
 (SELECT idimage from IMAGES ORDER BY id desc OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY) AS ROW2, 
 (SELECT idimage from IMAGES ORDER BY id desc OFFSET 2 ROWS FETCH NEXT 1 ROWS ONLY) AS ROW3, 
 (SELECT idimage from IMAGES ORDER BY id desc OFFSET 3 ROWS FETCH NEXT 1 ROWS ONLY) AS ROW4, 
 (SELECT idimage from IMAGES ORDER BY id desc OFFSET 4 ROWS FETCH NEXT 1 ROWS ONLY) AS ROW5
FROM IMAGES;

答案 2 :(得分:0)

使用LIMIT和ORDER BY将行限制为5。 检查实例How to concatenate text from multiple rows into a single text string in SQL server?以合并结果行