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

一道很有挑战性的SQL语句,想了好久没想到好的办法
如下表:
userID                 programId       answer
8177188 1 B
8177188 2 A
8177188 3 A
5802201 1 A
5802201 2 A
5802201 3 A
5962946 1 B
5962946 2 C
5962946 3 A
5211982 1 A
5211982 2 B
5211982 3 A
2051252 1 B
2051252 2 B
2051252 3 A
7088033 1 A
7088033 2 A
7088033 3 A
5571079 1 A
5571079 2 A
5571079 3 A
2127366 1 B
2127366 2 B
2127366 3 A
7994307 1 C
7994307 2 C
7994307 3 B
5718616 1 A
5718616 2 A
5718616 3 A
7110307 1 A
7110307 2 A
7110307 3 A


写SQL找出所有答案都正确的用户,如正确答案为1   B,2   B,3   A,就要找出所有答案为1   B,2   B,3   A的用户。

------解决方案--------------------
Select
A.*
From
TableName A
Inner Join TableName B
On A.userID = B.userID
Inner Join TableName C
On A.userID = C.userID
Where
A.programId = 1 And C.answer = 'B '
And
B.programId = 2 And C.answer = 'B '
And
C.programId = 3 And C.answer = 'A '
------解决方案--------------------
create table #t(userID int, programId int, answer varchar(10))
insert into #t
select 8177188,1, 'B ' union all
select 8177188,2, 'A ' union all
select 8177188,3, 'A ' union all
select 5802201,1, 'A ' union all
select 5802201,2, 'A ' union all
select 5802201,3, 'A ' union all
select 5962946,1, 'B ' union all
select 5962946,2, 'C ' union all
select 5962946,3, 'A ' union all
select 5211982,1, 'A ' union all
select 5211982,2, 'B ' union all
select 5211982,3, 'A ' union all
select 2051252,1, 'B ' union all
select 2051252,2, 'B ' union all
select 2051252,3, 'A ' union all
select 7088033,1, 'A ' union all
select 7088033,2, 'A ' union all
select 7088033,3, 'A ' union all
select 5571079,1, 'A ' union all
select 5571079,2, 'A ' union all
select 5571079,3, 'A ' union all
select 2127366,1, 'B ' union all
select 2127366,2, 'B ' union all
select 2127366,3, 'A ' union all
select 7994307,1, 'C ' union all
select 7994307,2, 'C ' union all
select 7994307,3, 'B ' union all
select 5718616,1, 'A ' union all
select 5718616,2, 'A ' union all
select 5718616,3, 'A ' union all
select 7110307,1, 'A ' union all
select 7110307,2, 'A ' union all
select 7110307,3, 'A '


select userID
from #t as A
where programId = 1 and answer = 'b '
and exists (select * from #t where userID=A.userID and programId = 2 and answer = 'b ')
and exists (select * from #t where userID=A.userID and programId = 3 and answer = 'A ')

drop table #t

/*

--结果

2051252
2127366

*/
------解决方案--------------------
Create Table TEST
(userID Varchar(10),
programId Int,
answer Varchar(3))
Insert TEST Select '8177188 ', 1, 'B '
Union All Select '8177188 ', 2, 'A '
Union All Select '8177188 ', 3, 'A '
Union All Select '5802201 ', 1, 'A '
Union All Select '5