如何在SQL语句中每周获取最新记录

时间:2015-05-27 03:11:05

标签: sql sql-server date sql-server-2005

我正在尝试每周一次从SQL Server 2005数据库导出最新记录。这是我的表:

hdd1

如何创建输出表应该是这样的:

agent_name  date          ID
ALEX        2015-05-25    13
ALEX        2015-05-22    13
ALICE       2015-05-24    10
ALICE       2015-05-26    10

我的SQL脚本:

agent_name  date          ID
ALEX        2015-05-25    13
ALICE       2015-05-26    10

4 个答案:

答案 0 :(得分:1)

这将返回从当前周的第一天到当周的最后一天的记录

   SELECT a.agent_name  
          ,a.date 
          ,a.ID 
   FROM Payment a INNER JOIN agentmaster b 
        ON a.ID = b.ID2 
   WHERE b.agent ='Y' AND 
         (a.date BETWEEN 
                 DATEADD(wk, DATEDIFF(wk, 0, GetDate()),0) AND
                 DATEADD(wk, DATEDIFF(wk, 0, GETDATE()),6))

答案 1 :(得分:1)

试试这个

SELECT ID, Agent_Name, MAX(Date) Max_Date
FROM AgentMaster
GROUP BY Agent_Name, ID

如果要添加日期过滤器,请添加where条件

date >= DATEADD(day,-7, GETDATE())

答案 2 :(得分:1)

如果您想要每个IDagent_name的最新行,请使用此代码:

SELECT a.agent_name,  
       MAX(a.[date]) [date], 
       a.ID
FROM Payment a 
GROUP BY
    a.agent_name,  
    a.ID

如果您希望每周都有最新的行,请使用以下命令:

SELECT a.agent_name,  
       a.date, 
       a.ID
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY DATEPART(WEEK, [date]) ORDER BY [date] DESC) seq
      FROM Payment ) a 
WHERE
    seq = 1

如果您想要每周IDagent_name的最新行,请使用以下内容:

;WITH p AS (
    /* add your query here */
)
SELECT a.agent_name,  
       a.date, 
       a.ID
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY agent_name, ID, DATEPART(WEEK, [date]) ORDER BY [date] DESC) seq
      FROM p ) a 
WHERE
    seq = 1

答案 3 :(得分:0)

在此解决方案中,我在CTE中创建了一个表,并定义了一段时间内的第一天。然后在几周的第一天和我们的实际查询之间制作一个JOIN

示例数据

DECLARE @tbl TABLE(agent_name VARCHAR(10) ,[date] date, Id INT)

INSERT @tbl
SELECT 'ALEX'  ,      '2015-05-25'  ,  13 UNION
SELECT 'ALEX'  ,      '2015-05-22'  ,  13 UNION
SELECT 'ALICE' ,      '2015-05-24'  ,  10 UNION
SELECT 'ALICE' ,      '2015-05-26'  ,  10

SELECT * FROM @tbl

查询

-- This period can be changed
DECLARE @StartDate date = '01/01/2015'
DECLARE @EndDate date = '01/01/2016'

;WITH Numbers (Number)
AS
(
  SELECT number
  FROM master..spt_values
  WHERE [type] = 'P'
 )
,firstDayOfWeek (fWDate)
AS
(
  SELECT DATEADD(DAY, n.Number, @StartDate)
  FROM Numbers AS n
  WHERE n.Number <= DATEDIFF(DAY, @StartDate, @EndDate)
  AND DATEPART(WEEKDAY, DATEADD(DAY, n.Number, @StartDate)) = 1 --Defines first day of week
 )
SELECT t.agent_name, Max(t.date) AS [date], t.Id
FROM @tbl AS t
INNER JOIN firstDayOfWeek AS fw ON t.date >= fw.fWDate
AND t.[date] < DATEADD(DAY, 7, fw.fWDate)
GROUP BY t.Id, t.agent_name