2011-04-04 62 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'