开发者

SQL Select Query Logic with 2 Parts

EDIT : I Want to Join the following Queries

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)
开发者_运维百科

WITH

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

The syntax Should be as follows

Select all from QUERY1 JOINED WITH QUERY2 WHERE QUERY2 doesn't record any records. I.e. if QUERY2 returns true than never mind returned the record from the first part

Select * from QUERY1 WHERE NOT EXISTS JOIN QUERY2 where @userId and @programmeId in query 2 come from QUery1


You could use outer apply to find the top 1 row matching your conditions:

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


Is this what you mean?

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜