SQL group by Query不起作用

时间:2017-07-18 14:24:12

标签: sql sql-server sql-server-2008 tsql group-by

我有两个非常相似的查询,一个是有效的,另一个一直在给我一个关于未包含在group by子句中的项目的错误,即使它是。这两个问题几乎是"几乎"相同,除了1场。我比较了上下两个,无法弄清楚为什么第二个不起作用

这个工作得很好:

SELECT o.Org+'-'+o.OrgSUB as 'orgsub',o.PSO,count(g.id) as caseNo,
 grouping(o.Org+'-'+o.OrgSUB ) AS ORGSUBTOTAL, grouping(o.PSO) AS PSOTOTAL 
 from g,o
        where  g.ORG+'-'+g.ORGSUB = o.ORG+'-'+o.ORGSUB and o.active='y' and 
  GROUP BY o.Org+'-'+o.OrgSUB ,o.PSO 
  WITH ROLLUP ORDER BY o.Org+'-'+o.OrgSUB desc, o.PSO desc, ORGSUBTOTAL , PSOTOTAL

现在,如果我替换PSO和ORG(以便结果显示ORG,然后组合org和orgsub一起,我得到以下错误:

专栏' o.orgsub'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

 SELECT o.Org+'-'+o.OrgSUB as 'orgsub',o.org,count(g.id) as caseNo,
     grouping(o.Org+'-'+o.OrgSUB ) AS ORGSUBTOTAL, grouping(o.org) AS orgTOTAL 
     from g,o
            where  g.ORG+'-'+g.ORGSUB = o.ORG+'-'+o.ORGSUB and o.active='y' and 
      GROUP BY o.Org+'-'+o.OrgSUB ,o.Org
      WITH ROLLUP ORDER BY o.Org+'-'+o.OrgSUB desc, o.Org desc, ORGSUBTOTAL , OrgTOTAL

如果我将GROUP BY o.Org+'-'+o.OrgSUB ,o.Org更改为GROUP BY o.Org+'-'+o.OrgSUB ,o.Org, o.OrgSub,则错误会消失,但我会遇到额外的行,我无需查看。

2 个答案:

答案 0 :(得分:0)

我的变化不大。我会这样做:

SELECT o.Org+'-'+o.OrgSUB as orgsub
     , o.PSO
     , count(g.id) as caseNo
     , grouping(o.Org+'-'+o.OrgSUB ) AS ORGSUBTOTAL
     , grouping(o.PSO) AS PSOTOTAL 
FROM  g JOIN o
ON  (g.ORG = o.ORG) 
AND (g.ORGSUB = o.ORGSUB)
WHERE o.active='y' 
GROUP BY orgsub, o.PSO 
WITH ROLLUP 
ORDER BY orgsub desc, o.PSO desc, ORGSUBTOTAL , PSOTOTAL 

我不知道您为什么这样做:o.Org+'-'+o.OrgSUB as 'orgsub'我将其更改为o.Org+'-'+o.OrgSUB as orgsub。我想测试它,但我希望它确实有用。

答案 1 :(得分:0)

我的猜测是,在你的小组中通过查询反复出现o.org会使其冒犯。为了简化(并使其更容易阅读),您可以创建一个视图:

CREATE VIEW orgSubView AS 
   SELECT o.Org+'-'+o.OrgSUB as orgsub, o.org as org, o.PSO as pso, g.id as caseNo 
   FROM g,o 
   WHERE g.ORG+'-'+g.ORGSUB = o.ORG+'-'+o.ORGSUB and o.active='y'

(或将此查询拉入新表..)然后通过查询运行您的组:

SELECT orgsub, pso ,count(caseNo)
FROM orgSubView 
GROUP BY orgsub ,pso

GROUP BY orgsub, org

然后添加额外的位(汇总和分组),如果可行的话。