SQL Server-每个GROUP BY表达式必须包含至少一个不是外部引用的列

时间:2018-08-22 15:48:21

标签: sql-server group-by count inner-join

我需要确定所有具有MostRecent = -1,OilWell = -1的记录,以及具有相同Api的重复记录,并将它们合并以获得关联的CompanyName。

查询:

SELECT 
    BLMAPDCONTACT.CompanyName, APD.Api, APD.ID, APD.MostRecent, 
    APD.Project_Nu, APD.Unit_Lease, APD.Well_Nu, APD.OilWell
FROM 
    APD 
INNER JOIN 
    BLMAPDCONTACT ON APD.BLM_APD_Cont = BLMAPDCONTACT.OBJECTID
WHERE 
    (APD.Api IN (SELECT APD.Api 
                 FROM APD AS Tmp 
                 WHERE APD.MostRecent = -1 AND APD.OilWell = -1 
                 GROUP BY APD.Api 
                 HAVING Count(APD.Api) > 1))
ORDER BY 
    APD.Api DESC;

我收到此错误:

  

每个GROUP BY表达式必须至少包含一列,而不是外部引用。

我添加了JOIN子句后出现了此错误;没有它,它会起作用。

所需的示例输出将与APD表中的以下记录匹配:

APD.Api | APD.MostRecent | APD.OilWell
--------------------------------------
123     | -1             | -1
123     | -1             | -1

不是:

APD.Api | APD.MostRecent | APD.OilWell
--------------------------------------
321     | 0              | -1
321     | -1             | -1

2 个答案:

答案 0 :(得分:1)

您尝试过这种方法吗?

SELECT BLMAPDCONTACT.CompanyName, APD.Api, APD.ID, APD.MostRecent, APD.Project_Nu, APD.Unit_Lease, APD.Well_Nu, APD.OilWell
FROM APD INNER JOIN BLMAPDCONTACT ON APD.BLM_APD_Cont = BLMAPDCONTACT.OBJECTID
WHERE (APD.Api IN 
    (SELECT tmp.Api 
    FROM APD As Tmp 
    WHERE tmp.MostRecent=-1 AND tmp.OilWell=-1 
    GROUP BY tmp.Api HAVING Count(tmp.Api)>1))
ORDER BY APD.Api DESC;

答案 1 :(得分:0)

别名和表名让我有些困惑。如果运行以下命令,是否还会出现相同的错误?

SELECT b.CompanyName
, a.Api
, a.ID
, a.MostRecent
, a.Project_Nu
, a.Unit_Lease
, a.Well_Nu
, a.OilWell
FROM APD a INNER JOIN BLMAPDCONTACT b
ON a.BLM_APD_Cont = b.OBJECTID
WHERE a.Api IN (
    SELECT tmp.Api 
    FROM APD As Tmp 
    WHERE tmp.MostRecent = -1 AND tmp.OilWell = -1 
    GROUP BY tmp.Api
    HAVING Count(tmp.Api) > 1
    )
ORDER BY a.Api DESC;

此外,只需仔细检查一下我是否已将表正确转换为别名即可。