内部查询结果的GROUP BY无法正常工作

时间:2018-08-01 10:24:06

标签: sql sql-server

我想对内部查询的结果进行GROUP BY ACCOUNTNO。

SELECT * 
FROM (SELECT O.CUSTADDRESSID, O.ACCOUNTNO, D.ORGANISATIONNAME
      FROM db.sc.TP_CUSTOMER_ADDRESSES O FULL OUTER JOIN
           db.sc.TP_CUSTOMER_BUSINESS D 
      ON O.ACCOUNTNO = D.ACCOUNTNO
     ) a 
GROUP BY ACCOUNTNO 
ORDER BY ACCOUNTNO;

但是我收到此错误:

  

信息8120,第16级,状态1,第1行
      选择列表中的“ a.CUSTADDRESSID”列无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。

需要帮助。谢谢。

2 个答案:

答案 0 :(得分:1)

您需要删除“ GROUP BY ACCOUNTNO”-查询如下:

SELECT * FROM (SELECT
   O.CUSTADDRESSID, O.ACCOUNTNO,
   D.ORGANISATIONNAME
FROM
   db.sc.TP_CUSTOMER_ADDRESSES O    FULL OUTER JOIN db.sc.TP_CUSTOMER_BUSINESS D ON O.ACCOUNTNO = D.ACCOUNTNO) a 
ORDER BY ACCOUNTNO

或列出分组依据的所有列-查询如下:

SELECT * FROM (SELECT
       O.CUSTADDRESSID, O.ACCOUNTNO,
       D.ORGANISATIONNAME
    FROM
       db.sc.TP_CUSTOMER_ADDRESSES O    FULL OUTER JOIN db.sc.TP_CUSTOMER_BUSINESS D ON O.ACCOUNTNO = D.ACCOUNTNO) a 
    GROUP BY ACCOUNTNO, CUSTADDRESSID, ORGANISATIONNAME
    ORDER BY ACCOUNTNO

答案 1 :(得分:1)

“分组依据”和“选择分组”不相同,这是一个示例:

SELECT ACCOUNTNO, CUSTADDRESSID, ORGANISATIONNAME FROM (
  SELECT
   O.CUSTADDRESSID, O.ACCOUNTNO,
   D.ORGANISATIONNAME
   FROM
   db.sc.TP_CUSTOMER_ADDRESSES O    FULL OUTER JOIN db.sc.TP_CUSTOMER_BUSINESS D ON O.ACCOUNTNO = D.ACCOUNTNO
   ) a 
 GROUP BY ACCOUNTNO, CUSTADDRESSID, ORGANISATIONNAME  ORDER BY ACCOUNTNO