当我有不同值的列时,如何获得不同的结果

时间:2012-05-07 06:29:48

标签: sql-server sql-server-2005

我有两张桌子,其中一张是“请求”,我有用户向我发送过朋友请求,或者我收到了朋友请求。在第二个表中,我记录了自己的入围用户。现在,我想要一起选择所有这些用户(我要求的人,请求我的人,我已入围的用户)。我正在使用联合查询,并根据列类型

区分它们
select Distinct userid,type,status from
(
select RequestSenderId as UserId,'requestedme' as type,'1' as status from tblrequest where RequestReceiverId=@UserId 

union
select RequestReceiverId as UserId,'requestedbyme' as type,'2' as status from tblrequest where RequestSenderId=@UserId 

union
select Shortlisteduserid as UserId,'Shortlisted' as type,'0' as status from tblshortlist where userid=@UserId
)

问题是我没有获得明确的用户ID,如果我也将其列入候选名单,他也向我发送了请求。

任何人都可以建议如何从结果中获取不同的用户ID。优先级是按要求获取用户标识而不是列入候选名单。

3 个答案:

答案 0 :(得分:0)

这可以帮到你。

select userid,type,status from
(
select Distint  RequestSenderId ,'requestedme' as type,'1' as status from tblrequest where ReceiverId=@UserId 

union ALL
select Distint  RequestReceiverId ,'requestedbyme' as type,'2' as status from tblrequest where SenderId=@UserId 

union ALL
select Distint  Shortlisteduserid ,'Shortlisted' as type,'0' as status from tblshortlist where userid=@UserId
)

答案 1 :(得分:0)

以下怎么样?它可能不是最有效的解决方案..

WITH requestedMe (userid, type, status)
    AS (
        SELECT RequestSenderId AS UserId,'requestedme' AS type,'1' AS status 
        FROM tblrequest 
        WHERE ReceiverId=@UserId)
    requestedByMe (userid, type, status)
    AS (
        SELECT RequestReceiverId AS UserId,'requestedbyme' AS type,'2' AS status 
        FROM tblrequest 
        WHERE SenderId=@UserId
            AND NOT EXISTS (
                SELECT *
                FROM requestedMe
                WHERE requestedMe.userid = tblrequest.RequestReceiverId))
    shortListed (userid, type, status)
    AS (
        SELECT Shortlisteduserid AS UserId,'Shortlisted' AS type,'0' AS status 
        FROM tblshortlist 
        WHERE userid=@UserId
            AND NOT EXISTS (
                SELECT *
                FROM requestedMe
                WHERE requestedMe.userid = tblshortlist.Shortlisteduserid)
            AND NOT EXISTS (
                SELECT *
                FROM requestedByMe
                WHERE requestedByMe.userid = tblshortlist.Shortlisteduserid))
SELECT userid, type, status
FROM requestedMe
UNION
SELECT userid, type, status
FROM requestedByMe
UNION
SELECT userid, type, status
FROM shortListed

答案 2 :(得分:0)

您可以使用排名功能(ROW_NUMBER或DENSE_RANK)来确定结果的优先级。

SELECT UserId, Type, Status
FROM (
    SELECT UserId, Type, Status
    , Priority = ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY Type DESC)
    FROM (
        SELECT ReceiverId, RequestSenderId, 'requestedme', 1 FROM tblRequest
        UNION ALL
        SELECT SenderId, RequestReceiverId, 'requestedbyme', 2 FROM tblRequest
        UNION ALL
        SELECT UserId, Shortlisteduserid ,'Shortlisted', 0 FROM tblShortlist
    ) U (FilterUserId, UserId, Type, Status)
    WHERE FilterUserId = @UserId
) R
WHERE Priority = 1