让子查询返回一行而不是一列

时间:2012-12-11 11:49:37

标签: sql

我有这个问题:

SELECT 
    [Address]=e.Address, 
    [LastEmail] = 
    (
        SELECT TOP 1 [Email] 
        FROM Email innerE 
        WHERE e.UserID = innerE.UserID 
        AND innerE.Contact = @emailId
        AND (IsSent is null OR isSent = 0)
        ORDER BY Timestamp DESC
    )

FROM Emails e

这很好,但是现在,我意识到我想要包含该lastemail列的整行,如果可能的话,是否可以做任何想法?

2 个答案:

答案 0 :(得分:1)

你可以这样做:

;WITH LastEmails
AS
(
   SELECT *, 
     ROW_NUMBER() OVER(ORDER BY Timestamp DESC) rownum
   FROM Emails
   WHERE Contact = @emailId
     AND (IsSent is null OR isSent = 0)
)
SELECT * FROM LastEmails
WHERE rownum = 1;

答案 1 :(得分:0)

如果您的DBMS支持它,您可以使用APPLY(我认为它看起来像SQL-Server语法)

SELECT  [Address]=e.Address, 
        [LastEmail] = ie.Email
FROM    Emails e
        OUTER APPLY
        (   SELECT  TOP 1 *
            FROM    Email innerE 
            WHERE   e.UserID = innerE.UserID 
            AND     innerE.Contact = @emailId
            AND     (IsSent is null OR isSent = 0)
            ORDER BY Timestamp DESC
        ) ie

这类似于相关子查询,但允许多行和多列。