SQL查询选择最后一行

时间:2011-09-07 16:11:02

标签: sql

我在SQL Server数据库中有一个表,其结构如下:

enter image description here

我想创建一个查询,它将选择早于参数日期的最后一行 我输入,按ID_Club分组,表示查询结果如下:

4, 1, 166013.01, 343697.42, 748231.00, 2011-02-28,
8, 2, 331408.11, 6981028.26, 738000.00, 2011-02-28,
etc...

我可以进行类似的查询,不是最后一行,而是总和。它看起来像:

select ID_Club, SUM(Cash), SUM(Less), SUM(InWay) 
from dbo.Period 
where DateEnd<'2011-03-01' 
GROUP BY ID_Club

2 个答案:

答案 0 :(得分:3)

不太确定如何阅读您的问题。您只想在指定日期之前获得最新记录吗?或者在日期之前的所有记录?

如果是所有记录,那么只需删除聚合函数并删除group-by子句,最后用:

SELECT * FROM dbo.Period WHERE DateEnd < '2011-03-01';

如果您只想要最近的记录:

SELECT TOP 1 * FROM dbo.Period WHERE DateEnd < '2011-03-01' ORDER BY DateEnd DESC;

答案 1 :(得分:1)

查看SQL OVER clause when used with PARTITION s

SELECT ID_Club, DateStart, DateEnd, Cash, Less, InWay
FROM Period p 
    INNER JOIN 
        (SELECT ID_Period, ROW_NUMBER() OVER (PARTITION by ID_CLUB ORDER BY ID_Period DESC) as RowNum
         FROM Period
               WHERE DateEnd<'2011-03-01') AS x
         ON p.ID_Period = x.ID_Period
WHERE x.RowNum = 1 -- Find just the last row in each partition

如果在您指定的日期范围内俱乐部有任何其他非零期间记录,您的“SUM”查询将失败

出于兴趣,下一版本的SQL(Denali)允许您在分区中请求“FIRST”或“LAST”记录,从而节省嵌套连接的工作量

更新:测试DDL / DML

create table Period 
(
ID_Period INT, 
ID_Club INT, 
DateStart DATETIME, 
DateEnd DATETIME, 
Cash MONEY, 
Less MONEY,
InWay MONEY
)

insert into Period (ID_Period, ID_Club, DateStart, DateEnd, Cash, Less, InWay )
VALUES (1, 1, 2010-08-01, 2010-08-31, 0, 0, 0)
insert into Period (ID_Period, ID_Club, DateStart, DateEnd, Cash, Less, InWay )
VALUES (2, 1, 2010-08-01, 2010-08-31, 166013.01, 343697.42, 748231.00)
insert into Period (ID_Period, ID_Club, DateStart, DateEnd, Cash, Less, InWay )
VALUES (3, 2, 2010-08-01, 2010-08-31, 0, 0, 0)
insert into Period (ID_Period, ID_Club, DateStart, DateEnd, Cash, Less, InWay )
VALUES (4, 2, 2010-08-01, 2010-08-31, 331408.11, 6981028.26, 738000.00 )