在和之间使用

时间:2012-04-06 14:47:15

标签: sql sql-server-2008

SELECT TOP 5 Notices.Id, NoticeL.Notices_Id, Loc.Id as Location_Id,
CAST(Notices.Text AS TEXT) as Text, CAST(Notices.Title AS TEXT) as Title,
Notices.CDate as RegDate 

FROM NoticeL JOIN Notices ON NoticeL.Notices_Id=Notices.Id
JOIN Loc ON NoticeL.Loc_Id=Loc.Id
WHERE Loc_Id IN (1) BETWEEN '06/04/2012' AND '23/04/2012'

我试图在IN之间使用,但我没有运气。我收到以下语法错误:

   Msg 156, Level 15, State 1, Line 1
   Incorrect syntax near the keyword 'BETWEEN'.

我猜MsSql不喜欢语法。我怎么能这样做?

第二个问题,我想在过去两周内过滤通知。无论如何,我可以在mssql中动态执行此操作。谢谢你的帮助。

4 个答案:

答案 0 :(得分:2)

 SELECT TOP 5 Notices.Id,
              NoticeL.Notices_Id, 
              Loc.Id as Location_Id,
              CAST(Notices.Text AS TEXT) as Text,
              CAST(Notices.Title AS TEXT) as Title,
              Notices.CDate as RegDate
 FROM NoticeL 
 JOIN Notices ON NoticeL.Notices_Id=Notices.Id JOIN Loc ON NoticeL.Loc_Id=Loc.Id
 WHERE Loc_Id IN (1) 
 AND Notices.CDate BETWEEN '06/04/2012' AND '23/04/2012'

您无法在同一字段中组合IN和BETWEEN。我猜测需要在Notices.CDate上使用Between,因为这似乎是唯一的日期字段。

如果你想抓住最后两周的价值,那么最后一行会改为

 AND Notices.CDate BETWEEN GETDATE() - 14 AND GETDATE()

如果查询中的时间问题,那么您可能想要做一些事情来消除GETDATE()的时间。这个问题似乎有一些好的答案。

How to return the date part only from a SQL Server datetime datatype

答案 1 :(得分:2)

NoticeL.Loc_Id=Loc.Id WHERE Loc_Id = 1 -- IN (1) should work too
                                      -- if you're building the query 
                                      -- dynamically as a string and want 
                                      -- to use IN with a list of IDs 
AND Notices.CDate BETWEEN '06/04/2012' AND '23/04/2012

过去两周(意味着过去14个日历日)你可以做到

AND Notices.CDate BETWEEN DATEADD(d,-14,GETDATE()) AND GETDATE()

答案 2 :(得分:2)

我认为你错过了AND,试试这个

FROM NoticeL JOIN Notices ON NoticeL.Notices_Id=Notices.Id
JOIN Loc ON NoticeL.Loc_Id=Loc.Id
WHERE Loc_Id IN (1) AND BETWEEN '06/04/2012' AND '23/04/2012'

答案 3 :(得分:0)

试试这个

    SELECT TOP 5 Notices.Id, NoticeL.Notices_Id, Loc.Id as Location_Id,
CAST(Notices.Text AS TEXT) as Text, CAST(Notices.Title AS TEXT) as Title,
Notices.CDate as RegDate 

FROM NoticeL JOIN Notices ON NoticeL.Notices_Id=Notices.Id
JOIN Loc ON NoticeL.Loc_Id=Loc.Id
WHERE Loc_Id IN (1) HAVING RegDate BETWEEN '06/04/2012' AND '23/04/2012'