我需要从已完成2个或多个类给下面的表格结构中的所有用户USER_NAME ...如何加入一个表只有结果有特定参数
table users
===============================
user_id | user_name
===============================
1234 completed_two
1235 completed_cero
1236 completed_one
1237 completed_two_no_survey
table class_registration
========================================================================
reg_id | class_id | class_type | user_id | attendance
========================================================================
1 1 stress 1234 1
2 1 stress 1236 1
3 2 who_cares 1234 1
4 1 stress 1235 0
5 5 nutrition 1236 1
6 9 who_cares_2 1237 1
7 10 return_of_the_care 1237 1
table surveys
==================================================================
survey_id | user_id | class_id | survey_type
==================================================================
1 1234 1 'Pre Workshop Survey'
2 1236 1 'Pre Workshop Survey'
3 1235 1 'Pre Workshop Survey'
4 1236 2 'Pre Workshop Survey'
5 1234 1 'Post Workshop Survey'
6 1236 2 'Post Workshop Survey'
在此示例中,USER_ID 1234有一类who_cares,考勤次数设为1,所以这个计数对于1个班级。压力类型有额外的要求,主要是在调查表中必须完成一项后期调查。具有user_id的用户也参加了2个班,但对于压力班而言,缺少调查。 user_id为1235的用户注册了压力班,但未能出席。
结果应该包含用户名称completed_two和completed_two_no_survey,因为这2个用户总共有2个班级参加了即使寿,用户1237没有调查。只有class_type压力或class_type营养才有调查。
我甚至不知道从哪里开始做这样的查询......我确定有一个案例我可以在那里展开,但我不知道如何使它只有压力和根据调查表检查营养。我想是这样的,在某处有一个CASE子句...
SELECT users.user_name FROM class_registration
JOIN users ON users.user_id = class_registration.user_id
WHERE class_registration.attendance = 1
GROUP BY class_registration.user_id, users.user_name
HAVING COUNT(class_registration.attendance) >= 2
同样,我需要的是检查调查表后车间的调查,当且仅当class_type是压力或营养。
感谢您的快速响应。我现在明白了如何做到这一点:) – jesusOmar 2011-03-07 18:02:43
@jesusOmar好,我刚刚意识到我使用了SQL Server特定的表变量。但只要你明白我做了什么,你就可以在你使用的任何东西中使用它。 – 2011-03-07 18:10:35