sql union sum与不同的描述字段

时间:2015-10-15 12:20:29

标签: sql sql-server

我有以下SQL:

select  distinct cat, sum(cnt)
from
(
select distinct prcIncidentManagement.CallCategory cat, count(eFolder.eFolderName) cnt
from prcIncidentManagement
inner join eFolder
on prcIncidentManagement.EFOLDERID=eFolder.eFolderID
group by prcIncidentManagement.CallCategory

union all

select distinct prcRequestFulfilment.CallCategory cat, count(eFolder.eFolderName) cnt
from prcRequestFulfilment
inner join eFolder
on prcRequestFulfilment.EFOLDERID=eFolder.eFolderID
group by prcRequestFulfilment.CallCategory
) results
order by 1

我发现很难对总数进行求和并将其与呼叫类别进行分组,因为错误消息如下:

  

列'results.cat'在选择列表中无效,因为它不是   包含在聚合函数或GROUP BY子句

无论如何?

2 个答案:

答案 0 :(得分:2)

删除distinct并在外部查询中添加GROUP BY

select  cat, sum(cnt)
from
(
    select prcIncidentManagement.CallCategory cat, count(eFolder.eFolderName) cnt
    from prcIncidentManagement
    inner join eFolder
    on prcIncidentManagement.EFOLDERID=eFolder.eFolderID
    group by prcIncidentManagement.CallCategory
    union all
    select prcRequestFulfilment.CallCategory cat, count(eFolder.eFolderName) cnt
    from prcRequestFulfilment
    inner join eFolder
    on prcRequestFulfilment.EFOLDERID=eFolder.eFolderID
    group by prcRequestFulfilment.CallCategory
) results
GROUP BY cat
order by 1;

添加和聚合函数时,可以选择不在group by子句中或聚合函数中的额外列。

此外,子查询中不需要DISTINCT具有聚合函数,因为它是无用的,因为group by将为您提供具有聚合函数的不同列,以聚合每个列的其他列小组,所以你不需要它。

答案 1 :(得分:0)

如果我假设eFolderName永远不会NULLeFolderId具有正确的外键关系(这两者都是非常合理的假设),那么您可以通过删除基础来简化查询加入子查询:

select cat, sum(cnt)
from ((select im.CallCategory as cat, count(im.eFolderID) as cnt
       from prcIncidentManagement im
       group by im.CallCategory
      ) union all
      (select f.CallCategory as cat, count(im.eFolderID) as cnt
       from prcRequestFulfilment f
       group by f.CallCategory
      ) 
     ) results
group by cat
order by cat;