编辑:我想加入以下查询
QUERY1
SELECT r.userId, r.programmeId, u.email, u.firstName, u.lastName, u.profileId, tblProgrammes.name, u.storeId, r.dateEnded AS lastPass, r.dateExpired
FROM tblUserRepeatHistory AS r INNER JOIN
tblUsers AS u ON r.userId = u.id INNER JOIN
tblProgrammes ON r.programmeId = tblProgrammes.id
WHERE (u.storeId = @storeId) AND (r.userId = @userId)
GROUP BY r.userId, r.programmeId, u.email, u.firstName, u.lastName, u.profileId, tblProgrammes.name, u.storeId, r.dateEnded, r.dateExpired
HAVING (DATEDIFF(D, MAX(r.dateExpired), GETDATE() + 31) >= 0)
使用
QUERY2
SELECT TOP (1) r.id, p.maxSteps
FROM tblUserQuestionnaireHistory AS r INNER JOIN
tblProgrammes AS p ON r.programmeId = p.id AND r.stepId = p.maxSteps
WHERE (r.userId = @UserId) AND (r.programmeId = @ProgrammeId) AND (r.success = 1)
ORDER BY r.id DESC
语法应如下
从QUERY1中选择全部与QUERY2联合WHERE QUERY2不记录任何记录。即如果QUERY2返回true,则从不介意从第一部分返回记录
从QUERY1中选择* WHERE NOT EXISTS JOIN QUERY2其中查询2中的@userId和@programmeId来自QUery1
答案 0 :(得分:0)
您可以使用outer apply
查找符合条件的top 1
行:
select *
from tblUserRepeatHistory u
outer apply
(
select top 1 *
from tblUserQuestionnaireHistory r
on r.userId = u.UserId
and r.programmeId = u.programmeId
and r.success = 1
and r.stepId = 9
) as r
答案 1 :(得分:0)
这是你的意思吗?
SELECT r.userId, r.programmeId, u.email, u.firstName, (SELECT TOP (1) r.id FROM tblUserQuestionnaireHistory AS r WHERE (r.userId = urh.UserId) AND (r.programmeId = urh.ProgrammeId) AND (r.success = 1) AND r.stepId = 9)
FROM tblUserRepeatHistory urh
where urh.UserId = @UserId and usr.ProgrammeId = @programmeId