日期:2014-05-17  浏览次数:20614 次

请教这个SQL语句要怎么写
本帖最后由 aisq2008 于 2013-11-17 21:22:50 编辑
现在有一张表,表中记录的内容是某个产品各个测试项目的测试结果,如果该产品的所有测试项目都通过,那么该产品合格,否则产品不合格。表内容如下,

id producId  testItem  isOk

1, 1001,    'Item1',   1
2, 1001,    'Item2',   0
3, 1001,    'Item3',   0
4, 1001,    'Item4',   1
                   
5, 1002,    'Item1',   1
6, 1002,    'Item2',   1
7, 1002,    'Item3',   1
8, 1002,    'Item4',   1
                   
9, 1003,    'Item1',   1
10, 1003,    'Item2',  1
11, 1003,    'Item3',  1
12, 1003,    'Item4',  1

现在的问题是:怎么用sql语句查出每个产品合格情况,无论是合格还是不合格,都要查出来。
sql

------解决方案--------------------

create table sq
(id int,producId int,testItem varchar(10),isOk int)

insert into sq
 select 1,1001,'Item1',1 union all
 select 2,1001,'Item2',0 union all
 select 3,1001,'Item3',0 union all
 select 4,1001,'Item4',1 union all          
 select 5,1002,'Item1',1 union all
 select 6,1002,'Item2',1 union all
 select 7,1002,'Item3',1 union all
 select 8,1002,'Item4',1 union all        
 select 9,1003,'Item1',1 union all
 select 10,1003,'Item2',1 union all
 select 11,1003,'Item3',1 union all
 select 12,1003,'Item4',1


select a.producId,
       case when exists(select 1 from sq b 
                        where b.producId=a.producId and isOk=0) then '不合格'
       else '合格' end '产品合格情况'
 from sq a
 group by a.producId
 
/*
producId    产品合格情况
----------- ------
1001        不合格
1002        合格
1003        合格

(3 row(s) affected)
*/