SQL中的WHERE仅允许1个子句

时间:2017-04-28 19:25:53

标签: sql

我收到错误

  Msg 102
  ',' -

附近的语法不正确

之后添加任何WHERE条件后

o.Status = 'Open'

如果我从MAXReceiveDate, MAXDateEnt, o.PartNo子句中取出WHERE,则会运行查询,但我需要这个标准。

DECLARE @now DATETIME
DECLARE @90daysago DATETIME

SET @now = GETDATE()
SET @90daysago = DATEADD(day, -90, @now)

SELECT
    MAX(r.ReceiveDate) AS MaxReceiveDate,
    MAX(po.DateEnt) AS MaxDateEnt,
    MAX(po.PONum) AS MaxPONum,
    o.JobNo, o.PartNo, o.Status
FROM 
    OrderDet as o
INNER JOIN 
    PODet as pod ON o.PartNo = pod.PartNo
INNER JOIN 
    Receiver as r ON pod.PONum = r.POnum
INNER JOIN 
    PO as po ON pod.PONum = po.PONum
WHERE
    o.Status = 'Open',
    MAXReceiveDate <= @90daysago,
    MAXDateEnt <= @90daysago,
    PartNo = '72347'
GROUP BY 
    o.PartNo, o.JobNo, o.Status

2 个答案:

答案 0 :(得分:7)

您必须将WHERE子句与AND连接,而不是,

WHERE
    o.Status = 'Open'
    AND MAXReceiveDate <= @90daysago
    AND MAXDateEnt <= @90daysago
    AND PartNo = '72347'

答案 1 :(得分:1)

如前面的评论所述,您不能在WHERE子句中使用聚合别名。你需要一个人去做你想做的事情。尝试类似:

DECLARE @now DATETIME
DECLARE @90daysago DATETIME

SET @now = GETDATE()
SET @90daysago = DATEADD(day, -90, @now)

SELECT
      MAX(r.ReceiveDate) AS MaxReceiveDate
    , MAX(po.DateEnt) AS MaxDateEnt
    , MAX(po.PONum) AS MaxPONum
    , o.JobNo
    , o.PartNo
    , o.[Status]
FROM OrderDet as o
INNER JOIN PODet as pod
    ON o.PartNo = pod.PartNo
INNER JOIN Receiver as r
    ON pod.PONum = r.POnum

INNER JOIN PO as po
    ON pod.PONum = po.PONum
WHERE
    o.Status = 'Open'
    AND o.PartNo = '72347'
GROUP BY o.PartNo, o.JobNo, o.[Status]
HAVING 
    MAX(r.ReceiveDate) <= @90daysago
    AND MAX(po.DateEnt) <= @90DaysAgo