根据条件创建额外的列(求和时为情况)

问题描述 投票:0回答:1

我有一个调查表,其中大约有人被问到5个问题。这些问题中有4个是相同的问题,但是由于他们了解自己的购买方式,因此答案的选择也有所不同。

这里是问题:

 ID                Question                            qid                         Answer
 101005 what brands did you purchase the past 5 months  1          Coca-Cola or Pepsi or Dr.Pepper
 101005 what brands did you purchase the past 5 months  1                       Dr.Pepper
 101005 what brands did you purchase the past 5 months  1                      store brand
 101005 what brands did you purchase the past 5 months  1                      Coca-Cola

目标是根据他们的答案创建四个额外的列,并且它们将被分配为1或0。由于此人的答案是可口可乐,所以我想在current_buyer列中为其分配,并给它们1和0分别是new_buyer列。我还想确保即使他在第二行回答了Dr.Pepper,它仍然将他识别为current_buyer。同样,我想在第3列中将此人分配为饮酒者,在前景中将第4列分配为0。

这里是表格的外观

  ID             Question                             qid               answer                    Current_buyer    New_buyer   drinker    prospect      
 101005 what brands did you purchase the past 5 months  1        Coca-Cola or Pepsi or Dr.Pepper      1               0             1        0
 101005 what brands did you purchase the past 5 months  1                       Dr.Pepper             0               1             0        1

目标是查看ID在过去5个月中是否购买了可口可乐,他们是当前的购买者(1)和饮酒者(1),并且在整个配置文件中将有(0)个new_buyer和潜在客户。

这是我尝试的代码:

 select ID,qid,question,answer,s_date,   
 Case when Sum(Case when [answer] like'%coca-cola%' then 1 else 0 end)>=1 then 1 
 else 0 end  current_buyer
 ,Case when Sum(Case when [answer] like'%coca-cola%' then 1 else 0 end)=0 then 1 
  else 0 end  New_buyer 
 ,Case when Sum(Case when [answer] like'%coca-cola,Dr.pepper,pepsi%' then 1 else 0 end)>=1 then 1 
  else 0 end  drinker
 ,Case when Sum(Case when [answer] like'%coca-cola,Dr.pepper,pepsi%' then 1 else 0 end)=0 then 1 
  else 0 end  Prospect

[不幸的是,即使人们选择了可口可乐,使用该代码我在饮酒者栏中也得到0。任何帮助,将不胜感激。

sql sql-server sum case
1个回答
0
投票

您是否需要类似的东西:

select ID,qid,question,answer,s_date,   
 Case when Sum(Case when [answer] like'%coca-cola%' then 1 else 0 end)>=1 then 1 
 else 0 end  current_buyer
 ,Case when Sum(Case when [answer] like'%coca-cola%' then 1 else 0 end)=0 then 1 
  else 0 end  New_buyer 
 ,Case when Sum(Case when [answer] like'%coca-cola%' OR [answer] like '%Dr.pepper%' OR [answer] like '%pepsi%' then 1 else 0 end)>=1 then 1 
  else 0 end  drinker
 ,Case when Sum(Case when [answer] like'%coca-cola,Dr.pepper,pepsi%' then 1 else 0 end)=0 then 1 
  else 0 end  Prospect
© www.soinside.com 2019 - 2024. All rights reserved.