读书人

求高手解答一个多条件都符合的才查出的

发布时间: 2012-03-18 13:55:39 作者: rapoo

求高手解答一个多条件都符合的才查出的SQL~

姓名 科目
张三 英语
张三 数学
张三 语文
李四 英语
李四 数学
王五 英语

我在前台获取条件个数

科目是英语 数学 语文 科目都有的人才能查询出来 结果应为张三
也有可能符合是 英语 数学 结果张三 李四
科目是 英语 物理 结果 查询没有符合人数
请问高手 这个SQL应该如何写~

[解决办法]

SQL code
if not object_id('Tempdb..#T') is null    drop table #TGoCreate table #T([姓名] nvarchar(2),[科目] nvarchar(2))Insert #Tselect N'张三',N'英语' union allselect N'张三',N'数学' union allselect N'张三',N'语文' union allselect N'李四',N'英语' union allselect N'李四',N'数学' union allselect N'王五',N'英语'GoSelect * from #T twhere exists(select 1             from #t             where [姓名]=t.[姓名] and [科目] =N'英语')and   exists(select 1             from #t             where [姓名]=t.[姓名] and [科目] =N'数学')and   exists(select 1             from #t             where [姓名]=t.[姓名] and [科目] =N'语文')/*姓名   科目---- ----张三   英语张三   数学张三   语文(3 row(s) affected)*/ 

读书人网 >SQL Server

热点推荐