【发布时间】:2020-02-27 01:58:16
【问题描述】:
我有一个调查表,有人被问到大约 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
101005 how many people live in your house 4 4
101005 what is your prefer retailers 8 walmart
目标是根据他们的答案创建四个额外的列,他们将被分配一个 1 或 0。由于此人的答案是可口可乐,我想将它们分配到 current_buyer 列中并给他们 1 和 0 将成为 new_buyer 列。我还想确保即使他在第二行回答 Dr.Pepper,它仍然将他识别为 current_buyer。同时,我想将此人在第 3 列中指定为 1 作为饮酒者,在第 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 1 0 1 0
101005 how many people live in your house 4 4 1 0 1 0
目标是查看 ID 在过去 5 个月内是否购买过可口可乐,他们是当前买家 (1) 和饮酒者 (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,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 if-statement sum case