开发者

sql server case problem

I have a table product having 3 columns maker holding values{'HCL','ACER',HP} model_no PK type {PC,Printer,laptop} I want to produce result set in following columns maker,pc,printer,laptop if a maker has prouct of the above category display yes in respective column else No The following code displays yes to all even if maker has no products It is req to use while and break statements.Please help me

select maker,'PC'= 
 case type
when 'pc' then 'Yes' 
when 'printer' then 'Yes'
when 'Laptop' then 'Yes'
else 'No'
end, 
'Laptop'= 
case type
when 'pc' then 'Yes' 
when 'printer' then 'Yes'
when 'Laptop' then 'Yes'
else 'No'
end,'Printer'=
case开发者_开发技巧 type
when 'pc' then 'Yes'
when 'printer' then 'Yes'
when 'Laptop' then 'Yes'
else 'No'
end  from product where maker='ACER'


select maker,
 case when type IN ('PC','Workstation','Server') THEN 'Yes' ELSE 'No' END AS PC,
 case when type IN ('Laptop','Tablet','Something') THEN 'Yes' ELSE 'No' END AS Laptop,
 case when type IN ('Printer','Plotter','Inkjet') THEN 'Yes' ELSE 'No' END AS Printer

from product 
where maker='ACER'

I took the liberty of changing your logic around. Put whatever conditions that valid a 'Yes' in each IN statement, then add as many as you need/wish.


select 
  maker,
  case [type] when 'pc'      then 'yes' else 'no' end as PC,
  case [type] when 'Laptop'  then 'yes' else 'no' end as Laptop,
  case [type] when 'Printer' then 'yes' else 'no' end as Printer
from product
where maker = 'ACER'


Try this:

        select maker,
        case type when 'pc' then 'Yes'  when 'printer' then 'Yes' when 'Laptop' then 'Yes'      else 'No' end AS PC, 
case type when 'pc' then 'Yes'  when 'printer' then 'Yes' when 'Laptop' then 'Yes' else 'No' end AS Laptop,
case type when 'pc' then 'Yes' when 'printer' then 'Yes' when 'Laptop' then 'Yes' else 'No' end AS Printer 

from product where maker='ACER' 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜