SQL - 如何在特定日期之前按天选择日期?

时间:2015-04-28 15:34:10

标签: sql sql-server-2012

例如,假设我有5/2/2015作为我的终点。我想在结束点之前知道max(Thursday)。我怎样才能在4/30/2015结束。另外,我没有可供选择的列。

所以我的whereclause需要指定'2015年5月2日'

sql 2012

3 个答案:

答案 0 :(得分:1)

您可以尝试使用此While循环来实现您之后的目标:

SomeCodition()

答案 1 :(得分:0)

您可以使用WEEKDAY功能

SELECT TOP 1 column FROM table
WHERE WEEKDAY(column) = 5 AND column<'2015-05-02'
ORDER BY column DESC

答案 2 :(得分:0)

如果您需要在SELECT中运行它,可以使用以下命令:

SELECT 
    CAST(DATEADD(DAY, 
      CASE 
        WHEN DATEPART(WEEKDAY, GETDATE()) >= 5 
        THEN 5 - DATEPART(WEEKDAY, GETDATE())
        ELSE ((-2 - DATEPART(WEEKDAY, GETDATE()))) 
      END, GETDATE()) AS DATE) AS PreviousThursday

使用样本数据:

DECLARE @Sample TABLE
    (
        theDate DATETIME
    )

INSERT  @Sample
SELECT  '20100805' UNION ALL    -- Thursday
SELECT  '20100806' UNION ALL    -- Friday
SELECT  '20100807' UNION ALL    -- Saturday
SELECT  '20100808' UNION ALL    -- Sunday
SELECT  '20100809' UNION ALL    -- Monday
SELECT  '20100810' UNION ALL    -- Tuesday
SELECT  '20100811' UNION ALL    -- Wednesday
SELECT  '20100812' UNION ALL    -- Thursday
SELECT  '20100813' UNION ALL    -- Friday
SELECT  '20100814'      

SELECT 
    DATENAME(WEEKDAY, thedate), 
    thedate, 
    DATEADD(DAY, 
      CASE 
        WHEN DATEPART(WEEKDAY, theDate) >= 5 
        THEN 5 - DATEPART(WEEKDAY, theDate)
        ELSE ((-2 - DATEPART(WEEKDAY, theDate))) 
      END, theDate)
FROM @Sample

使用变量:

DECLARE @TheDate DATETIME = '5/2/2015'

SELECT 
    DATEADD(DAY, 
      CASE 
        WHEN DATEPART(WEEKDAY, @TheDate) >= 5 
        THEN 5 - DATEPART(WEEKDAY, @TheDate)
        ELSE ((-2 - DATEPART(WEEKDAY, @TheDate))) 
      END, @TheDate) AS PreviousThursday