获取最后4个星期五日期的SQL查询

时间:2014-08-21 07:00:40

标签: sql sql-server

我想从下表中获取最后4个星期五的日期。取决于用户输入计数将存储在另一个表中,并根据我想要获取日期的值。例如,如果计数为5,我想得到最后5个星期五的日期。

---------------------------------------------
  Id        |           fridaydate
---------------------------------------------
   1        |   2014-08-15 11:46:00.000   |

   2        |   2014-08-22 11:46:00.000   |

   3        |   2014-08-08 11:46:00.000   |

   4        |   2014-08-01 11:46:00.000   |

   5        |   2014-07-25 11:46:00.000   |

   6        |   2014-07-18 11:46:00.000   |

   7        |   2014-07-11 11:46:00.000   |

4 个答案:

答案 0 :(得分:1)

使用以下格式:

DECLARE @D INT= 5    -- User Input value

SELECT TOP (@D) *
FROM YourTable

您可以在存储过程中使用上述查询,如下所示:

Create Procedure YourProcedureName 
  @D int
as Begin
    SELECT TOP (@D) *
    FROM YourTable
    Order by fridaydate Desc
End

答案 1 :(得分:0)

这样的事情会:

select ca.*
from dbo.AnotherTable a
    cross apply (
        select top (a.FridayCount) *
        from dbo.FridayTable ft
        where ft.FridayDate <= getdate()
        order by ft.FridayDate desc
    ) ca
where a.UserId = @SomeUserId
order by ca.FridayDate desc;

答案 2 :(得分:0)

SELECT TOP @YourCount fridaydate FROM Table ORDER BY Id DESC

答案 3 :(得分:0)

SELECT top 5 datefield
FROM table
WHERE lower(datename(dw, datefield))='friday'
GROUP BY datefield
ORDER BY datefield desc