1

我有一个表需要被同一个表中的其他响应过滤。我使用以下有效的脚本,但是当“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' 
4

1 回答 1

0

如果 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)
于 2013-04-05T15:56:57.083 回答