我无法找出用于检索特定数据集的SQL语句。除了上次更新日期之外所有列都相同,我想要最新的。例如。
Book Author Update
John Foo 1/21/2010
John Foo 1/22/2010
Fred Foo2 1/21/2010
Fred Foo2 1/22/2010
检索最新行的查询是什么?也就是说,返回的查询:
Book Author Update
John Foo 1/22/2010
Fred Foo2 1/22/2010
TIA,
史蒂夫
答案 0 :(得分:4)
SELECT
book,
author,
MAX(update)
FROM
My_Table
GROUP BY
book,
author
这仅适用于此特定情况,因为其他列的所有具有相同的值。如果你想逐一获取最新的一行,但作者(或你将要检索的其他一些专栏)可能会有所不同,那么你可以使用:
SELECT
T.book,
T.author,
T.update
FROM
(SELECT book, MAX(update) AS max_update FROM My_Table GROUP BY book) SQ
INNER JOIN My_Table T ON
T.book = SQ.book AND
T.update = SQ.max_update
答案 1 :(得分:2)
修正了
DROP TABLE #tmpBooks
CREATE TABLE #tmpBooks
(
Book VARCHAR(100),
Author VARCHAR(100),
Updated DATETIME
)
INSERT INTO #tmpBooks VALUES ('Foo', 'Bar', '1/1/1980')
INSERT INTO #tmpBooks VALUES ('Foo', 'Bar', '1/1/1990')
INSERT INTO #tmpBooks VALUES ('Foo', 'Bar', '1/1/2000')
INSERT INTO #tmpBooks VALUES ('Foo', 'Bar', '1/1/2010')
INSERT INTO #tmpBooks VALUES ('Foo2', 'Bar2', '1/1/1980')
INSERT INTO #tmpBooks VALUES ('Foo2', 'Bar2', '1/1/1990')
INSERT INTO #tmpBooks VALUES ('Foo2', 'Bar2', '1/1/2000')
SELECT Book, Author, Max(Updated) as MaxUpdated
FROM #tmpBooks
GROUP BY Book, Author
结果:
Book Author MaxUpdated
--------------- --------------- -----------------------
Foo Bar 2010-01-01 00:00:00.000
Foo2 Bar2 2000-01-01 00:00:00.000
(2 row(s) affected)
答案 2 :(得分:1)
这将得到你所要求的,但有些东西告诉我这不是你想要的。
SELECT Book, Author, MAX(Update)
FROM BookUpdates
GROUP BY Book, Author
表架构还有更多内容吗?
答案 3 :(得分:0)
试试这个(没有要测试的数据,但它应该工作):
SELECT
bu.Book,
bu.Author
FROM
BookUpdates bu
JOIN
(SELECT MAX(Updated) as Date FROM BookUpdates) max
WHERE
bu.Updated = max.Date;