2011-04-04 65 views
0

我有3列{PC,打印机,笔记本电脑} 我要产生结果集 壶拿着值{ 'HCL', 'ACER',HP} model_no PK 类型的表产品以下列制造商,电脑,打印机,笔记本电脑 如果一个制造商产生上述类别显示在相应列中是yes 否则否 即使制造商没有产品,以下代码也会显示为yes 要求使用while和break请帮助我SQL Server的情况下,问题

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' 
+0

这功课吗? (如果是这样,请使用作业标签) – 2011-04-04 08:17:03

回答

-1

试试这个:

 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

-1这与OP已经做的没有什么不同。 – 2011-04-04 14:00:30

1
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' 

我花了大约改变你的逻辑的自由。在每个IN语句中加入任何有效'是'的条件,然后添加尽可能多的你需要的/希望的。

+0

-1您的代码无效。 '关键字'IN''附近的语法不正确。我想你不能在'case'语句中使用'IN'。 – 2011-04-04 14:06:58

+1

对不起,我忘记了case和type之间的“WHEN”,当你以后使用CASE和一个列名时,它期望一个WHEN'value' - 上面的代码应该运行良好,使用IN在CASE声明。 – cairnz 2011-04-04 19:51:07

0
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'