我有两个表ward1和ward2ie;
create table ward1
(
ward_id int
)
create table ward2
(
ward_id int,
ward_name varchar(10)
)
,值为 -
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');
所以我需要产生ward_id的总发生次数。对我来说这很简单,我使用了这段代码。
SELECT ward_id, count(ward_id) as "No of occurrence" from ward1 group by ward_id;
输出是 -
ward_id No of occurrence
101 2
102 3
这是来自ward1表的记录,但是当我需要来自表ward2的ward_name时。我收到了错误。 这是我的代码 -
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;
它不是表达群体......
我想这样显示 -
ward_id ward_name No of occurrence
101 child 2
102 General 3
请帮忙......
答案 0 :(得分:2)
关闭。您真的只需要在where子句中加入2个表(或使用首选的“join”语句)
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;
答案 1 :(得分:1)
您不需要HAVING
子句,只需使用WHERE
子句链接表格:
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;
您应该使用SQL-92语法而不是SQL-86,然后只需要添加JOIN
条件:
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;
希望它有所帮助...
答案 2 :(得分:0)
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;