读书人

这句SQL语句如何写

发布时间: 2012-01-10 21:26:50 作者: rapoo

这句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
--------------------------
1XX既得糖尿病又得高血的人
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 ( '糖尿病 ', '高血压 '))

读书人网 >SQL Server

热点推荐