1
SELECT
   o.id, o.Name, o.StageName, o.[Type], o.Account__c, o.SalesPerson__c,
   o2.AccountId__c,o2.Sales_Person__c, o2.InvoiceDate__c
FROM customers.dbo.sales as o 
INNER JOIN customers.dbo.account as a on a.Id = o.AccountId 
INNER JOIN
( 
    Select MAX(Id)Id, AccountId 
    FROM customers.dbo.order__c
    WHERE Sales_Person__c <> NULL
) as o1 
INNER JOIN Customers.dbo.Order__c as o2 on o2.Id = o1.Id
WHERE (o.SalesPerson__c = NULL) 
AND (o.[Type] = 'Renewal') 
AND (o.StageName NOT LIKE 'Closed%')

不知道我做错了什么。我收到以下错误:关键字“Where”附近的语法不正确

我正在尝试获取每个帐户的最新订单。任何帮助将不胜感激。

4

2 回答 2

2

您的问题是<> NULL and = NULL,您需要使用IS NULLor IS NOT NULL。根据您的 RDBMS,您还需要GROUP BY在子查询中使用MAX()

select o.id
    , o.Name
    , o.StageName
    , o.[Type]
    , o.Account__c
    ,o.SalesPerson__c
    , o2.AccountId__c
    , o2.Sales_Person__c
    , o2.InvoiceDate__c
from customers.dbo.sales as o 
Inner Join customers.dbo.account as a 
    on a.Id = o.AccountId 
INNER JOIN
(
    Select MAX(Id)Id, AccountId 
    from customers.dbo.order__c
    where Sales_Person__c IS NOT NULL
    GROUP BY AccountId -- depending on the RDBMS you need a GROUP BY
) o1 
INNER JOIN Customers.dbo.Order__c  o2 
    on o2.Id = o1.Id
Where (o.SalesPerson__c IS NULL) 
    and (o.[Type] = 'Renewal') 
    and (o.StageName NOT LIKE 'Closed%')
于 2012-07-25T15:37:49.737 回答
2

您称为 o1 的内部联接不会加入任何内容。我不确定你到底想做什么,但我认为如果你删除inner joinfor o1,而是exists在你的where子句中使用它,它可能会更好。您还必须更改您的 o2 join 以 join on o2.AccountId = a.Id,我认为这是您正在尝试做的。

select o.id
, o.Name
, o.StageName
, o.[Type]
, o.Account__c
, o.SalesPerson__c
, o2.AccountId__c
, o2.Sales_Person__c
, o2.InvoiceDate__c
from customers.dbo.sales as o 
Inner Join customers.dbo.account as a 
    on a.Id = o.AccountId 
INNER JOIN Customers.dbo.Order__c as o2 
    on o2.AccountId = a.Id
Where (o.SalesPerson__c is NULL) 
and (o.[Type] = 'Renewal') 
and (o.StageName NOT LIKE 'Closed%')
and exists(
    Select MAX(Id) as id 
    from customers.dbo.order__c c
    where c.Sales_Person__c is not NULL
    and id = o2.id)
于 2012-07-25T15:54:31.383 回答