我有一个表需要通过同一个表中的其他响应进行过滤。我使用以下脚本,但是当有'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'
答案 0 :(得分: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)