1

I need to use a single query to get the first 5 values as a single row of results. I am aware that the following does not work but I think it gives a good example of what I am trying to achieve

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

Does anyone know the best way to achieve this. I am sure the syntax must be pretty simple but i cant seem to find it.

Christopher Vickers
  • 1,773
  • 1
  • 14
  • 18

3 Answers3

1

You can use conditional aggregation:

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;

Note that SQL tables represent unordered sets. The ? in the order by is for the column that specifies the ordering.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

If I understand correctly what you want to do, maybe you can use some subquery this way:

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;
Ass3mbler
  • 3,855
  • 2
  • 20
  • 18
0

use LIMIT and ORDER BY to restrict your rows to 5. Check for instance How to concatenate text from multiple rows into a single text string in SQL server? to concatanate the resulting rows

lpp
  • 26
  • 1