每年根据前一排日期一个最大日期排

时间:2018-08-07 15:07:37

标签: sql tsql

我有一个包含两列的表,我想使用规则获取6年的数据

  1. 第一行将是最大日期行,该行之前等于输入日期(我将通过输入日期)

  2. 从第二行到第六行,我需要的最大值(日期行)早于上一行数据选择的数据,并且同一年不应有2行,我只需要根据上一行的最新行,但不在同一年。

       declare @tbl table (id int identity, marketdate date )
    
       insert into @tbl (marketdate)
       values('2018-05-31'),
             ('2017-06-01'),
             ('2017-05-28'),
             ('2017-04-28'),
             ('2016-05-26'),
             ('2015-04-18'),
             ('2015-04-20'),
             ('2015-03-18'),
             ('2014-05-31'),
             ('2014-04-18'),
             ('2013-04-15')
    

输出:

id  marketdate
1    2018.05.31
3    2017.05.28
5    2016.05.27
7    2015.04.20
9    2014.04.18
10   2013.04.15

4 个答案:

答案 0 :(得分:1)

您不能通过/ desc的简单命令来完成此操作吗?

SELECT TOP 6 id, max(marketdate) FROM tbl

WHERE tbl.marketdate <= @date

GROUP BY YEAR(marketdate), id, marketdate

ORDER BY YEAR(marketdate) DESC

答案 1 :(得分:1)

纯粹基于给定样本数据的“输出”,我相信以下是您所追求的(每个数据年份的最大日期):

SELECT TOP 6   
  max(marketdate),
  Year(marketDate) as marketyear
FROM @tbl
WHERE @tbl.marketdate <= getdate()
GROUP BY YEAR(marketdate)
ORDER BY YEAR(marketdate) DESC;

SQLFiddle of this matching your output

答案 2 :(得分:1)

如果您使用的是SQL Server,则可以使用row_number

select      top 6
            id
            , t.marketdate
from        (   select  rn = row_number() over (partition by year(marketdate)order by marketdate desc)
                        , id
                        , marketdate
                from    @tbl) as t
where       t.rn = 1
order by    t.marketdate desc

答案 3 :(得分:0)

以下内容递归搜索下一个日期,该日期必须比上一个日期至少早一年。

您的参数化开始位置位于我选择的2018-06-01处。

WITH
  recursiveSearch AS
(
  SELECT
    id,
    marketDate
  FROM
  (
    SELECT
      yourTable.id,
      yourTable.marketDate,
      ROW_NUMBER() OVER (ORDER BY yourTable.marketDate DESC)  AS relative_position
    FROM
      yourTable
    WHERE
      yourTable.marketDate <= '2018-06-01'
  )
    search
  WHERE
    relative_position = 1

  UNION ALL

  SELECT
    id,
    marketDate
  FROM
  (
    SELECT
      yourTable.id,
      yourTable.marketDate,
      ROW_NUMBER() OVER (ORDER BY yourTable.marketDate DESC)  AS relative_position
    FROM
      yourTable
    INNER JOIN
      recursiveSearch
        ON  yourTable.marketDate < DATEADD(YEAR, -1, recursiveSearch.marketDate)
  )
    search
  WHERE
    relative_position = 1
)
SELECT
  *
FROM
  recursiveSearch
WHERE 
  id IS NOT NULL
ORDER BY
  recursiveSearch.marketDate DESC
OPTION
  (MAXRECURSION 0)

http://sqlfiddle.com/#!18/56246/13