读书人

这样的SQL语句该如何写

发布时间: 2012-03-30 17:32:09 作者: rapoo

请教大家这样的SQL语句该怎么写?
学生表student

stuid name age

01 xp 20
02 pan 12


学生属性表

id stuid type

1 01 A
2 01 b
3 01 C
4 02 A
5 02 C


如何得到type是既是A、又是B、又是C的学生(即01号学生)。

依次类推,如何根据客户对type的输入,得到相应的查询记录。比如客户输入A、C就得到既是A又是C的学生(即01和02),客户输入A、B就得既是A、又是B的学生(即01)

[解决办法]

--假入的是 'A,B,C '的字符串
Declare @type Varchar(1000)
Select @type = 'A,B,C '
Select stuid From 学生属性表 Where CharIndex(type, @type) > 0 Group By stuid Having Count(stuid) = Len(@type) - Len(Replace(@type, ', ', ' ')) + 1
[解决办法]
select stuid , count(*) cnt from
(
select distinct stuid,type from 学生属性表 where type = 'A '
union all
select distinct stuid,type from 学生属性表 where type = 'B '
union all
select distinct stuid,type from 学生属性表 where type = 'C '
) t
group by stuid having count(*) = 3
[解决办法]
create procedure sp_getstuid(@id char)--假入的字符串之间的分格符是,
as
Declare @type Varchar(1000)
Select @type = @id
Select stuid From 学生属性表 Where CharIndex(type, @type) > 0 Group By stuid Having Count(stuid) = Len(@type) - Len(Replace(@type, ', ', ' ')) + 1
go

读书人网 >SQL Server

热点推荐