Question

I made a query that get all rooms with its name, its address, and other data.

(select replace(wm_concat( '\par \tab ' || s.address|| '\par \tab ' || s.lib || '\par \tab '), ',', '\par - ')
 from t_room s)

Too long for all the data, the only one important data are the name and the address.

The fact is, 2 rooms can have the same address, so in result I don't want :

room1 address1 - room2 address1

that, I actually get, but

room1 address1 - room2 at the same address

is this possible in oracle 10?

I tried adding a distinct for the address field, but of course not possible.

Thank you.

Was it helpful?

Solution

You can achieve that using LAG function:

CREATE TABLE t_room_s (
  room VARCHAR2(20),
  address VARCHAR2(20)
);

INSERT INTO t_room_s VALUES ('room1', 'addr 1');
INSERT INTO t_room_s VALUES ('room2', 'addr 1');
INSERT INTO t_room_s VALUES ('room3', 'addr 2');
INSERT INTO t_room_s VALUES ('room4', 'addr 3');
INSERT INTO t_room_s VALUES ('room5', 'addr 4');
INSERT INTO t_room_s VALUES ('room6', 'addr 4');
INSERT INTO t_room_s VALUES ('room7', 'addr 4');
INSERT INTO t_room_s VALUES ('room8', 'addr 5');

SELECT wm_concat(room || ' ' || addr) AS val
  FROM (
    SELECT
        room,
        CASE
          WHEN LAG(address, 1, NULL) OVER (ORDER BY address) = address THEN 'same address'
          ELSE address
        END AS addr
      FROM
        t_room_s
    ORDER BY address
  )
;

Output:

VAL
-------------------------------------------------------------------------------------------------------------------------
room1 addr 1,room2 same address,room3 addr 2,room4 addr 3,room5 addr 4,room6 same address,room7 same address,room8 addr 5
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top