2
| id |
+----+
| 1  |
| 2  |
| 4  |
| 5  |
+----+

Output as row

1 2 4 5

Without use of Pivot method ,no hardcoding like checking with case with when 1 = 1.No dynamic Sql .with out any inbuilt function.

I have searched questions but could not find anything in pure sql Is there a way?

Dot Net Dev 19
  • 345
  • 2
  • 12

4 Answers4

1

Most SQL databases support some sort of group concatenation ability. For example, in MySQL we could use GROUP_CONCAT:

SELECT GROUP_CONCAT(id ORDER BY id SEPARATOR ' ') AS output
FROM yourTable;

The ANSI standard may not define anything, but SQL Server, Oracle, and Postgres, to name a few, can do something similar to the above.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

I would use correlated subquery & do conditional aggergation since some DBMS doesn't have a row_number() :

SELECT MAX(CASE WHEN Seq = 1 THEN Id END) AS ID1,
       . . . 
       MAX(CASE WHEN Seq = 4 THEN Id END) AS ID4
FROM (SELECT t.*,
             (SELECT COUNT(*) FROM table t1 WHERE t1.id <= t.id) AS Seq
      FROM table t
     ) t;

However, this method might fail if the ID is not in Sequential manner if so, then you would need to use PK (IDENTITY Column) that specify column ordering.

Yogesh Sharma
  • 49,870
  • 5
  • 26
  • 52
1

Maybe your database supports the LISTAGG function of ANSI SQL:2016: It is a function to transform values from a group of rows into a delimited string.

See syntax as well as database support and alternatives here:

Listagg is an ordered set function, which require the within group clause to specify an order. The minimal syntax is: LISTAGG(<expression>, <separator>) WITHIN GROUP(ORDER BY …)

hc_dev
  • 8,389
  • 1
  • 26
  • 38
0

If you know you have four values, you can use conditional aggregation:

select max(case when seqnum = 1 then id end) as id_1,
       max(case when seqnum = 2 then id end) as id_2,
       max(case when seqnum = 3 then id end) as id_3,
       max(case when seqnum = 4 then id end) as id_4       
from (select t.*, row_number() over (order by id) as seqnum
      from t
     ) t;

I'm not sure if this fits your requirements. If you are looking for something with a variable number of columns, then you need to use dynamic SQL.

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