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) 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

4 回答 4

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() 的时间。这个问题似乎有一些很好的答案。

如何仅从 SQL Server 日期时间数据类型返回日期部分

于 2012-04-06T14:53:40.350 回答
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()
于 2012-04-06T14:54:11.910 回答
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'
于 2012-04-06T14:57:54.920 回答
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'
于 2012-04-06T14:55:37.660 回答