¿Cómo fusionar registros de dos tablas usando grupo por cláusula en Oracle?

I have two tables ward1 and ward2ie;

create table ward1
(
ward_id int
)

create table ward2
(
ward_id int,
ward_name varchar(10)
)

and the values are --

insert into ward1 values(101);
insert into ward1 values(101);
insert into ward1 values(102);
insert into ward1 values(102);
insert into ward1 values(102);

insert into ward2 values(101,'child');
insert into ward2 values(102,'General');

So I need to produce total number of occurrence of ward_id.It was simple for me i used this code.

SELECT ward_id, count(ward_id) as "No of occurrence" from ward1 group by ward_id;

the output was --

ward_id   No of occurrence
101       2
102       3

this are the records from ward1 table, but when I want ward_name from the table ward2. I am getting error. This is my code--

select ward1.ward_id as "ward_id",ward2.ward_name,
count(ward1.ward_id)as "No of occurrence" from ward1,
ward2 group by ward1.ward_id,ward2.ward_name 
having ward1.ward_id=ward2.ward_id;

It says not a group by expression...

I want to display like this--

ward_id   ward_name    No of occurrence
101       child        2
102       General      3

Por favor, ayuda ....

preguntado el 10 de marzo de 12 a las 14:03

3 Respuestas

Close. You really just need to join the 2 tables in a where clause (or using the preferred "join" statement)

select ward1.ward_id as "ward_id",ward2.ward_name,
count(ward1.ward_id)as "No of occurrence" 
from ward1,ward2 
where ward1.ward_id = ward2.ward_id
group by ward1.ward_id,ward2.ward_name;

respondido 10 mar '12, 14:03

Ohh yeah that was close.Thank you. - ceniza dmc4

No quieres el HAVING clause here, just use a WHERE clause to link your tables:

select ward1.ward_id as "ward_id",
       ward2.ward_name,
       count(ward1.ward_id) as "No of occurrence" 
  from ward1,
       ward2
 WHERE ward1.ward_id = ward2.ward_id
 group by ward1.ward_id,
          ward2.ward_name;

You should really be using the SQL-92 syntax rather than SQL-86, then you just need to add the JOIN condición:

select ward_id,
       ward2.ward_name,
       count(ward_id) as "No of occurrence" 
  from ward1
 INNER JOIN ward2 USING (ward_id)
 group by ward_id,
          ward2.ward_name;

Espero que ayude ...

respondido 10 mar '12, 14:03

select ward1.ward_id as "ward_id",
       ward2.ward_name,
       count(ward1.ward_id) as "No of occurrence"
from   ward1, ward2
where  ward1.ward_id = ward2.ward_id
group by ward1.ward_id,ward2.ward_name;

respondido 10 mar '12, 14:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.