【发布时间】: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