2

我有这个查询:

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 列的整行,如果可能的话,有什么想法可以做到吗?

4

2 回答 2

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;
于 2012-12-11T11:53:16.717 回答
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

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

于 2012-12-11T12:09:17.700 回答