Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle equivalent to SQL Server STUFF function?

Tags:

select

oracle

Does Oracle have its own implementation of SQL Server stuff function?

Stuff allows you to receive one value from a multi row select. Consider my situation below

 ID   HOUSE_REF   PERSON
 1      A         Dave
 2      A         John
 3      B         Bob

I would like to write a select statement, but I want the PERSON names to be in a single row.

For example, when I select from this table, I want to achieve the following

HOUSE_REF   PERSONS
A           Dave, John
B           Bob

I haven't been able to find a simple solution so far, it may be a case of writing my own function to use, but I'm not entirely sure of how to approach this, any ideas?

The main business use of this, will be to have a select statement that shows each house, and against that house to have one column which lists everyone that lives in that house. The house ref in this select must be unique, hence needing to concatenate the persons

Thanks

like image 407
Jimmy Avatar asked Jan 21 '10 09:01

Jimmy


People also ask

What is the stuff function in SQL Server?

The STUFF function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.

What is all objects in Oracle?

ALL_OBJECTS describes all objects accessible to the current user. Related Views. DBA_OBJECTS describes all objects in the database. USER_OBJECTS describes all objects owned by the current user.

What are Oracle SQL functions?

A function is a subprogram that returns a value. The data type of the value is the data type of the function. A function invocation (or call) is an expression, whose data type is that of the function. Before invoking a function, you must declare and define it.

What is Wm_concat function in Oracle?

Normally, WM_CONCAT is an aggregate function that return values from table separated by comma like here. Suppose I have a table foo like this: col_id | col_text 111 | This 111 | is 111 | a 111 | test. If I use this query: SELECT CAST(WM_CONCAT(col_text) AS VARCHAR2(100)), col_id FROM foo.


2 Answers

Oracle 11.2 includes a new function LISTAGG to do this.

Prior to that you could use Tom Kyte's STRAGG function.

like image 97
Tony Andrews Avatar answered Jan 02 '23 21:01

Tony Andrews


The "no add-ons/no undocumented functions" Oracle solution (prior to 11.2 as Tony mentions) is:

select c1, ltrim(sys_connect_by_path(c2,','),',') persons
 from
  (
   select c1, c2, 
    row_number() over (partition by c1 order by c2 ) rn
     from
      (
       select house_ref c1, person c2 
        from housetable 
      )
   )
  where connect_by_isleaf=1
  connect by prior rn+1 =rn and prior c1 = c1
  start with rn=1
;
like image 37
dpbradley Avatar answered Jan 02 '23 19:01

dpbradley