0

我的数据库中有以下信息:

 TO | FROM |    DATE   |  PRICE
AAA |  BBB | 12/3/2012 |  $100
AAA |  CCC | 12/3/2010 |  $200
AAA |  BBB | 10/3/2010 |  $450
BBB |  CCC | 09/7/2010 |  $270
BBB |  AAA | 06/9/2011 |  $130
AAA |  CCC | 12/3/2013 |  $176

我想编写一个查询(或最好是 LINQ 表达式)来选择最近的 TO-FROM 对,因此根据上表,我希望在查询中返回以下数据:

 TO | FROM |    DATE   |  PRICE
AAA |  BBB | 12/3/2012 |  $100
BBB |  CCC | 09/7/2010 |  $270
BBB |  AAA | 06/9/2011 |  $130
AAA |  CCC | 12/3/2013 |  $176

做这个的最好方式是什么。

4

1 回答 1

0

由于您没有提到您的 RDBMS,因此下面的查询适用于大多数 RDBMS

SELECT a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT To, FROM, MAX(DATE) maxDate
            FROM tableName
            GROUP BY To, FROM
        ) b ON a.To = b.To AND
                a.FROM = b.FROM AND
                a.DATE = b.maxDATE

但如果你是 RDBMS 支持CTEWINDOWS FUNCTION

WITH latestRecord AS
(
SELECT [To], [FROM], DATE, Price,
        ROW_NUMBER() OVER (Partition BY [TO], [FROM] ORDER BY date DESC) rn
FROM tableName
)
SELECT [To], [FROM], DATE, Price
FROM latestRecord
WHERE rn = 1

或者WINDOWS FUNCTION ONLY

SELECT [To], [FROM], DATE, Price
FROM 
(
    SELECT [To], [FROM], DATE, Price,
            ROW_NUMBER() OVER (Partition BY [TO],[FROM] ORDER BY date DESC) rn
    FROM tableName
) s
WHERE rn = 1

还有一件事要指出,TO并且FROM有些保留关键字,它们必须使用转义字符进行转义,具体取决于RDBMS您使用的字符。

于 2012-12-18T01:52:06.250 回答