日期:2014-05-19  浏览次数:20507 次

这句SQL语句怎么写?
有两张表
A表:ID     姓名  
          1       张XX
          2       李XX
          ..     ..
B表:ID     疾病
          1       糖尿病
          1       高血压
          2       高血压
          ..     ....

A表是病人的基本信息,B表是病人患的疾病,有的人可能会得多种疾病。

现在需要查询:1。既得糖尿病又得高血压的人
                            2。得糖尿病却没有得高血压的人
                            3。既没有得糖尿病又没有得高血压的人
SQL语句怎么写?

------解决方案--------------------
3 Select A.*
From A
Inner Join B On A.ID = B.ID
where b.疾病 not in( '糖尿病 ', '高血压 ')
------解决方案--------------------
if object_id( 'a ')> 0
drop table a
if object_id( 'b ') > 0
drop table b


create table a (id int,name varchar(20))
insert into a
select 1, '張XX '
union all
select 2, '李XX '

create table b(id int,jibin varchar(20))
insert into b
select 1, ' 糖尿病 '
union all
select 1, '高血壓 '
union all
select 2, ' 高血壓 '

go

alter function fun_str(@id int)
returns varchar(200)
begin
declare @str varchar(200)
set @str= ' '
select @str=@str+ ', '+jibin from b where id=@id
set @str=stuff(@str,1,1, ' ')
return (@str)
end

go



select id,name,
case when charindex( '糖尿病 ',dbo.fun_str(id))> 0
and charindex( '高血壓 ',dbo.fun_str(id))> 0
then '既得糖尿病又得高血壓的人 '
when charindex( '糖尿病 ',dbo.fun_str(id))> 0
and charindex( '高血壓 ',dbo.fun_str(id))=0
then '得糖尿病沒有得高血壓的人 '
when charindex( '糖尿病 ',dbo.fun_str(id))=0
and charindex( '高血壓 ',dbo.fun_str(id))> 0
then '得糖尿病沒有得高血壓的人 '
end as jibin
from a
/*
id name jibin
--------------------------
1 張XX 既得糖尿病又得高血壓的人
2 李XX 得糖尿病沒有得高血壓的人
*/




------解决方案--------------------
直接用一條語句就可以實現的,沒必要寫個函數來實現。
------解决方案--------------------
select 姓名from A where id in(select 疾病from B where 疾病 in ( '糖尿病 ', '高血压 '))
select 姓名from A where id in(select 疾病from B where 疾病 in ( '糖尿病 ') and 疾病 <> '高血压 ')
select 姓名from A where id in(select 疾病from B where 疾病 not in ( '糖尿病 ', '高血压 '))