【问题标题】:Filter reponses by initial survey response按初始调查回复过滤回复
【发布时间】:2013-03-28 01:44:16
【问题描述】:

我有一个表需要被同一个表中的其他响应过滤。我使用以下有效的脚本,但是当“Customer.customer_id”(有时有)重复时,结果会出现偏差。我的问题是是否有更好的方法来重写此代码以避免这种情况,因此它只从“客户”表中选择不同的结果?

下面的示例表应该只返回“两个”响应,因为 customer_id '10' 有重复条目(基于下面的查询)

示例表:

[res_id]  [question_id]  [customer_id]  [survey_id]  [res_answer]
  1            20             10           155          male
  1            20             11           155          male
  1            20             10           155          male
  1            20             12           155          female

当前查询:

  SELECT
  Responses.res_id AS responseID
     ,Responses.res_col AS answer
    ,Responses.res_created AS dateCreated
    ,Responses.res_notes AS note
    ,Responses.question_id AS questionID
    ,Responses.customer_id AS customerID
    ,Responses.res_answer AS subQuestion
    ,Responses.survey_id AS surveyID
    ,Responses.res_void AS void
    ,Customer.res_answer AS filter
FROM
    Responses, Responses AS Customer
WHERE
    rs.customer_id = Customer.customer_id
AND
    Responses.survey_id ='155' 
AND
    Customer.survey_id = '155'
AND
    Responses.question_id = '20'                    

AND CAST(Customer.res_answer AS VARCHAR(500)) = 'male'
AND Responses.res_void = '0' 

【问题讨论】:

  • 请编辑您的问题标签以包含您正在使用的 dbms 和版本
  • @AaronKurtzhals tsql 很明显。
  • (1) 我认为您的平台是 MS SQL Server 是否正确? (2) 在您的示例中,我不明白您为什么认为它应该是 2 行。不应该是 3 行吗? (3) 您正在执行LEFT JOIN,然后使用您的WHERE rs.customer_id = Customer.customer_id 有效地将其转换为INNER JOIN。这是有原因的吗?
  • 你的表有主键列吗?
  • 抱歉在里面留下了一些测试代码,这并不是一个“左连接”语句。查询结果表以获取平均值和计数 f 或各种响应。

标签: sql-server tsql sql-server-2005


【解决方案1】:

如果 2005 年不支持 Distinct,则按

分组
SELECT Distinct 
     Responses.res_id AS responseID
    ,Responses.res_col AS answer
    ,Responses.res_created AS dateCreated
    ,Responses.res_notes AS note
    ,Responses.question_id AS questionID
    ,Responses.customer_id AS customerID
    ,Responses.res_answer AS subQuestion
    ,Responses.survey_id AS surveyID
    ,Responses.res_void AS void
    ,'male'
FROM Responses
WHERE Responses.survey_id ='155' 
  AND Responses.question_id = '20'  
  AND Responses.res_void = '0'                  
  AND exists (select 1 from Responses c 
              where c.res_answer = 'male' 
                and c.survey_id  = '155'
                and c.ID = Responses.ID)

【讨论】:

  • 不确定分组依据是一个选项,因为有些问题可能有多个响应,当根据主响应表检查 Customer.customer_id 时,原始帖子中的查询会下降。跨度>
  • 当前查询是否有效?是什么让您认为 group by 不是选项?这就是删除 Customer.customer_id 的原因。
  • 是的,当前查询仅在以下情况下有效. 我们对大约 50 个具有不同类型回答的问题进行了调查,我们通常按性别或年龄组过滤总回答(每个问题有多个回答)
猜你喜欢
  • 2018-12-17
  • 1970-01-01
  • 2012-09-01
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多