So, Here are the tables-
create table person (
id number,
name varchar2(50)
);
create table injury_place (
id number,
place varchar2(50)
);
create table person_injuryPlace_map (
person_id number,
injury_id number
);
insert into person values (1, 'Adam');
insert into person values (2, 'Lohan');
insert into person values (3, 'Mary');
insert into person values (4, 'John');
insert into person values (5, 'Sam');
insert into injury_place values (1, 'kitchen');
insert into injury_place values (2, 'Washroom');
insert into injury_place values (3, 'Rooftop');
insert into injury_place values (4, 'Garden');
insert into person_injuryPlace_map values (1, 2);
insert into person_injuryPlace_map values (2, 3);
insert into person_injuryPlace_map values (1, 4);
insert into person_injuryPlace_map values (3, 2);
insert into person_injuryPlace_map values (4, 4);
insert into person_injuryPlace_map values (5, 2);
insert into person_injuryPlace_map values (1, 1);
Here, table person_injuryPlace_map
will just map the both other tables.
How I wanted to show data is -
Kitchen Pct Washroom Pct Rooftop Pct Garden Pct
-----------------------------------------------------------------------
1 14.29% 3 42.86% 1 14.29% 2 28.57%
Here, the value of Kitchen, Washroom, Rooftop, Garden column is the total incidents happened. Pct columns will show the percentage of the total count.
How can I do this in Oracle SQL?
I did it like the following -
You need to use the standard PIVOT query.
Depending on your Oracle database version, you could do it in two ways:
Using PIVOT for version 11g and up:
Using MAX and DECODE for version 10g and before:
If you use Oracle 11g or above you can use pivot function for your required output.
You will have to first take the count and pct in a subquery then use max+decode function to summarize both of them in the required fashion Check if the below query helps: