Sql - 获取每个类别的最接近日期

时间:2014-12-15 15:17:19

标签: datetime sql-server-2008-r2 range

我正在尝试在Sql server 2008中编写一个T-SQL查询。我有一个表,我正在尝试查找每个类别中最接近今天的记录。

CREATE TABLE [dbo].[Spreads](
    [SpreadId] [int] NOT NULL PRIMARY KEY,
    [TeamName] [NVARCHAR](50),
    [BetAmt] [decimal](8, 2) NULL,
    [BetDate] [date] NULL)
GO



INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',5260024,171,'2013-07-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',5822695,106.5,'2013-08-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',6527717,142,'2013-09-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',7184393,177.5,'2013-10-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',7844000,213,'2013-11-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',8366731,248.5,'2013-12-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',8743888,284,'2014-01-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',9056722,319.5,'2014-02-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',9401025,355,'2014-10-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',9795365,390.5,'2014-11-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('EAGLES',10190748,426,'2014-12-13');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('COWBOYS',10608591,461.5,'2014-06-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('COWBOYS',10979252,497,'2014-07-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('COWBOYS',11375005,532.5,'2014-08-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('COWBOYS',11821325,568,'2014-09-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('COWBOYS',12222217,603.5,'2014-10-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('COWBOYS',12799249,639,'2014-11-03');
INSERT INTO dbo.SPREADS(TeamName,SpreadId, BetAmt, BetDate) VALUES('COWBOYS',13164980,674.5,'2014-12-03');

GO

如果没有类别,我会写下面的查询:

Declare @today DATETIME = GETDATE();  
SELECT TOP 1 DATEDIFF(D, betdate, @today), betdate, spreadid, TeamName, betamt from Spreads
ORDER BY 1 asc

这只返回1条记录,但我要找的是两条记录。对于上述数据,我希望我的查询返回spreadId为10190748和13164980的记录。

1 个答案:

答案 0 :(得分:0)

这是你要找的吗?

with RecentDate as (select SpreadID
                          ,TeamName
                          ,BetAmt
                          ,BetDate
                          ,ROW_NUMBER() over(PARTITION by TeamName order by betdate desc) row_n
                    from dbo.Spreads)
Select SpreadID
      ,TeamName
      ,BetAmt
      ,BetDate
from RecentDate
where row_n = 1