SQL GROUP BY用于嵌套的select语句

时间:2017-08-30 06:37:14

标签: sql oracle

以前我有这个查询 -

SELECT 
  COUNT(DISTINCT ds.CLIENTID),
  COUNT(ds.FACID),
  (SUM(ds.NETARREARS) + SUM(ds.TAXARREARS)),
  SUM(ds.UNEARNEDINCOME), 
  SUM(ds.INCOMESUSPENSE) , 
  SUM(ds.VATSUSPENSE) , 
  SUM(ds.PREPAIDDEPOSIT), 
  SUM(ds.NETFUTURE) , 
  SUM(ds.NETEXPOSURE), 
  SUM(ds.PROVISION), 
  SUM(ds.FACILITYSECURITYAMOUNT), 
  SUM(ds.PROVISIONAMOUNTCFWD) 

FROM 
  DAILY_SUMMARY ds 

WHERE
  ds.SUMMARY_DATE = :reportDate AND 
  ds.FACSTS IN('F','L','A') AND 
  ds.PERSTS = 'N';

但后来我们决定删除列

  1. ds.UNEARNEDINCOME(从顶部开始的第4个选项)
  2. ds.PROVISION(从第10位选择项目)
  3. 因为我们有其他查询来获取那些 -

    1. SELECT SUM(tcs.DUEAMT) FROM TCRENT tcs WHERE tcs.FACID = ds.FACID AND tcs.DUETYPE = 'INT' AND tcs.DUEDATE > :reportDate
    2. SELECT sum(pup.PROVISIONAMT) FROM PROVISION_UPLOAD pup WHERE pup.PROVISIONDATE < :reportDate AND pup.FACID = ds.FACID
    3. 所以最后的查询是 -

      SELECT 
        COUNT(DISTINCT ds.CLIENTID),
        COUNT(ds.FACID),
        (SUM(ds.NETARREARS) + SUM(ds.TAXARREARS)),
        (SELECT SUM(tcs.DUEAMT) FROM TCRENT tcs WHERE tcs.FACID = ds.FACID AND tcs.DUETYPE = 'INT' AND tcs.DUEDATE > :reportDate) AS income, 
        SUM(ds.INCOMESUSPENSE) , 
        SUM(ds.VATSUSPENSE) , 
        SUM(ds.PREPAIDDEPOSIT), 
        SUM(ds.NETFUTURE) , 
        SUM(ds.NETEXPOSURE), 
        (SELECT sum(pup.PROVISIONAMT) FROM PROVISION_UPLOAD pup WHERE pup.PROVISIONDATE < :reportDate AND pup.FACID = ds.FACID) AS prov, 
        SUM(ds.FACILITYSECURITYAMOUNT), 
        SUM(ds.PROVISIONAMOUNTCFWD) 
      
      FROM 
        DAILY_SUMMARY ds 
      
      WHERE
        ds.SUMMARY_DATE = '10-FEB-15' AND 
        ds.FACSTS IN('F','L','A') AND 
        ds.PERSTS = 'N';
      

      但现在问题是将这两个查询与主查询集成,它会给出错误 -

        

      不是单组组功能

      表示它需要GROUP BY。我尝试了分组,甚至生成了SQL Developer的建议组,但它不准确,因为它不完整 -

      group by COUNT(DISTINCT, COUNT(ds.FACID), (SUM(ds.NETARREARS), (SELECT,SUM(ds.INCOMESUSPENSE), 
      SUM(ds.VATSUSPENSE), SUM(ds.PREPAIDDEPOSIT), SUM(ds.NETFUTURE), SUM(ds.NETEXPOSURE), (SELECT
      

      仅供参考 - 如果group by子句和新的2个查询被评论,则主查询可以正常工作。

      任何人都可以帮我吗?

      更新 - 示例结果截图

      Sample result

1 个答案:

答案 0 :(得分:0)

问题是您的子查询是相关子查询

(SELECT sum(pup.PROVISIONAMT)
 FROM PROVISION_UPLOAD pup
 WHERE pup.PROVISIONDATE < :reportDate AND
       pup.FACID = ds.FACID
-------------------^
) AS prov, 

此关联子句正在使用ds.FACID。但是,此列在聚合之后不可用。

我不确定你真正想要的结果,因此很难提出解决方案。也许您希望在子查询中再次引用ds,而不是相关的子查询。