SQL查询日期=今天减去7天

时间:2017-03-06 20:50:23

标签: sql sql-server database between

我的网站上有一个名为ExternalHits的SQL表。我将URL跟踪为URLx,以及将页面作为Datex访问的日期。我每周都会运行此查询以获取前一周的总点击次数,并且每周我必须手动更改"之间的#34;日期。有什么方法可以改变我的查询,以便"之间的#34;日期是今天和今天的7?我不想每周手动更改日期。

    SELECT URLX, COUNT(URLx) AS Count
    FROM ExternalHits
    WHERE datex BETWEEN '02/27/2017' AND '03/05/2017'    
    GROUP BY URLx
    ORDER BY Count DESC; 

7 个答案:

答案 0 :(得分:13)

declare @lastweek datetime
declare @now datetime
set @now = getdate()
set @lastweek = dateadd(day,-7,@now)

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN @lastweek AND @now
GROUP BY URLx
ORDER BY Count DESC; 

答案 1 :(得分:5)

使用dateadd从当前日期删除一周。

Public Function newPOID(prefix As String, storedProcedure As String) As String

    Dim newId As String = prefix + "0001"
    Dim adpt As New SqlDataAdapter
    Dim ds As New DataSet
    Dim dr As SqlDataReader
    Dim conn As New SqlConnection
    conn.ConnectionString = conString
    utos = New SqlCommand(storedProcedure, conn)
    utos.CommandType = CommandType.StoredProcedure
    conn.Open()
    dr = utos.ExecuteReader

    If dr.Read Then
        If dr.IsDBNull(0) Then
            Dim num As Integer = 1
            'Dim prefix As String = "PO"
            Dim append As String = prefix + num.ToString().PadLeft(4, "000")
            newId = append
        Else
            Dim POstring As String = dr(0).ToString.Substring(0, 3)
            Dim POID As Integer = dr(0).ToString.Substring(5) + 1
            Dim append As String = POstring + POID.ToString().PadLeft(3, "000")
            newId = append
        End If
        conn.Close()
    End If


    Return newId

End Function

答案 2 :(得分:1)

使用内置功能:

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
GROUP BY URLx
ORDER BY Count DESC; 

答案 3 :(得分:0)

您可以使用CURDATE()DATE_SUB()功能来实现此目的:

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()    
GROUP BY URLx
ORDER BY Count DESC; 

答案 4 :(得分:0)

您可以使用以下内容从当前日期中减去7:

WHERE datex BETWEEN DATEADD(day, -7, GETDATE()) AND GETDATE()

答案 5 :(得分:0)

使用以下内容:

WHERE datex BETWEEN GETDATE() AND DATEADD(DAY, -7, GETDATE())

希望这有帮助。

答案 6 :(得分:0)

DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name

where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))