2017-07-18 87 views
-1

我有兩個查詢,它們非常相似,一個作品和另一個不斷向我提供有關未包含在group by子句中的項目的錯誤,即使它是。兩個查詢「幾乎」相同,除了1個字段。我比較了兩個上下想不通,爲什麼第二不起作用查詢中的SQL小組無法正常工作

這個工作得很好:現在

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然後通過組織的組合和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錯誤消失,但是我卡住了額外的行,我不需要看到它。

回答

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。我想測試它,但我希望它能夠工作。

+0

的o.PSO工作我改變你的查詢org和orgsub的組合,它沒有工作:( –

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 

添加您的額外位(彙總和分組)是否工作..