选择星期记录

时间:2013-04-16 04:37:55

标签: sql sql-server

我写了这个查询给了我当天的记录

SELECT EnquiryOwner,Count(uid) 
FROM EnquiryMaster 
WHERE orgid = '" + orgid + "' 
    AND (DAY(date) = DAY(GETDATE()) 
    AND MONTH(date) = MONTH(GETDATE()) 
    AND YEAR(date) = YEAR(GETDATE())) 
GROUP BY EnquiryOwner

我想选择一周的记录。如果我在星期二访问,我想要从上周二到本周二的记录

3 个答案:

答案 0 :(得分:3)

You can use dateadd to determine the date of one week before.

E.g。像

DAY(date)   = DATEADD(day,   -7, GETDATE()) AND    
MONTH(date) = DATEADD(month, -7, GETDATE()) AND
YEAR(date)  = DATEADD(year,  -7, GETDATE()) 

... WHERE date between DATEADD(DAY,-7,GETDATE()) and GETDATE()

另请参阅date and time functions列表。

答案 1 :(得分:2)

如果你不关心时间:

WHERE date between DATE_SUB(DATE(NOW()),INTERVAL 7 DAY) and DATE(NOW())

如果你关心时间:

WHERE date between DATE_SUB(NOW(),INTERVAL 7 DAY) and NOW()

这是MYSQL。对于SQL Server,它看起来像这样:

WHERE date between DATEADD(DAY,-7,GETDATE()) and GETDATE()

(我没有安装sql server,因此未经过测试。)

答案 2 :(得分:0)

如果你想跳一周,你只需要使用dateadd比较一个日期减去7。

SELECT EnquiryOwner,Count(uid) 
FROM EnquiryMaster 
WHERE orgid = '" + orgid + "' 
    AND date = DATEADD(date, -7, GETDATE()) 
GROUP BY EnquiryOwner