我的数据库中有以下信息:
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
最好的方法是什么。
答案 0 :(得分: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支持CTE
和WINDOWS 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
。