日期:2014-05-18  浏览次数:20784 次

在线等大虾帮我
有2张表 Country表和City表
create table Country
(
Country_code varchar(10),
Country_Name Varchar(20),
)
insert into Country values('CN','China'),
('US','U,S,A'),
('CA','Canada')
create table City
(
City_Code varchar(10),
City_Name Varchar(20),
Country_Code Varchar(10),
constraint PK_City Primary Key(City_Code)
)
insert into City values('BJ','BeiJin','CN'),
('SH','ShangHai','CN'),
('SZ','ShenZhen','CN'),
('BG','baiGong','US'),
('HSD','HuaShengDun','US'),
('DLD','DuoLunDuo','CA')
问:选择出城市个数大于1的国家名称? 小弟菜鸟求救啊! 如上面结果应该是China和U,S,A 在线等啊!

------解决方案--------------------
SQL code
select
   a.Country_Name
from
   Country a join City b
on
   a.Country_code=b.Country_code 
group by
   a.Country_Name
having
   count(1)>1

------解决方案--------------------
SQL code
create table Country
(
Country_code varchar(10),
Country_Name Varchar(20),
)
insert into Country values('CN','China'),
('US','U,S,A'),
('CA','Canada')
create table City
(
City_Code varchar(10),
City_Name Varchar(20),
Country_Code Varchar(10),
constraint PK_City Primary Key(City_Code)
)
insert into City values('BJ','BeiJin','CN'),
('SH','ShangHai','CN'),
('SZ','ShenZhen','CN'),
('BG','baiGong','US'),
('HSD','HuaShengDun','US'),
('DLD','DuoLunDuo','CA')
go
select a.country_name 
from Country a inner join City b on a.Country_code=b.Country_Code 
group by a.country_name
having COUNT(*)>1
/*
country_name
--------------------
China
U,S,A

(2 行受影响)

*/
go
drop table city,Country

------解决方案--------------------
SQL code
select
*
from  Country  as a 
where exists(select 1 from City where Country_code=a.Country_code having count(1)>1)