2015-10-21 124 views
1

我的數據是這樣的:SQL命令組按組分類彙總

SaleID ParentCo Subsidiary  Amount 
1   BigCo  Big A LTD  10 
2   MedCo  Medium Inc.  10 
3   BigCo  BigCo Corp.  10 
4   BigCo  Biggest Co.  10 
5   BigCo  Big A LTD  10 
6   MedCo  Medium LLC  10 
7   MedCo  Medium Inc.  10 
8   SmallCo  SmallCo   10 

我想顯示每個母公司和各子公司合計,下令DESC由母公司和嵌套地(就是一個字?)分組並通過子公司有序的,就像這樣:

ParentCo  Subsidiary SumOfAmount 
BigCo  (all)   40 
BigCo  Big A LTD  20 
BigCo  BigCo Corp 10 
BigCo  Biggest Co. 10 
MedCo  (all)   30 
MedCo  Medium Inc. 20 
MedCo  Medium LLC 10 
SmallCo  (all)   10 
SmallCo  SmallCo  10 

我已經得到了最遠的是這樣的:

SELECT [ParentCo], [Subsidiary], SUM([Amount]) AS SumOfAmount FROM [table] 
GROUP BY [ParentCo], [Subsidiary] 
WITH ROLLUP 
ORDER BY SumOfAmount DESC; 

但是任何知道任何東西的人都會看到,這是行不通的,因爲它顯示的是按SumOfAmount降序的所有行,而沒有將每個子公司的總數保持在其母公司總數以下(或者說高於或低於)。

我在想我可能需要某種嵌套查詢,但是,我是一個noob,上面是我寫過的最複雜的SQL。

在情況下,它很容易,它的工作一樣好,我可以顯示在單獨的列子公司和家長的款項,重複父母的總和各子公司旁邊:

ParentCo  Subsidiary SumOfSubsidiary SumOfParent 
BigCo  Big A LTD  20    40 
BigCo  BigCo Corp 10    40 
BigCo  Biggest Co. 10    40 
MedCo  Medium Inc. 20    30 
MedCo  Medium LLC 10    30 
SmallCo  SmallCo  10    10 

雖然我們它,一個相關的問題:

有沒有隻顯示總的每個母公司的一種方式,但在它旁邊,名稱和總金額爲其子公司,最大大部,像這樣:

ParentCo  SumOfParent LargestSubsidiary SumOfSubsidiary 
BigCo  40    Big A LTD   20 
MedCo  30    Medium Inc.  20 
SmallCo  10    SmallCo   10 

任何想法?提前致謝!

回答

1

您可以使用耦合CTESUM OVER()達到預期的排序:

WITH Cte AS(
    SELECT 
     ISNULL(ParentCo, 'ALL') AS ParentCo, 
     ISNULL(Subsidiary, 'ALL') AS Subsidiary, 
     SUM(Amount) AS SumOfAmount 
    FROM tbl 
    GROUP BY 
     ParentCo, Subsidiary 
    WITH ROLLUP 
), 
CteFinal AS(
    SELECT *, 
     sm = SUM(SumOfAmount) OVER(PARTITION BY ParentCo) 
    FROM Cte 
    WHERE 
     ParentCo <> 'ALL' 
) 
SELECT 
    ParentCo, Subsidiary, SumOfAmount 
FROM CteFinal 
ORDER BY 
    sm DESC, SumOfAmount DESC 

關於第二個問題,你可以簡單地使用SUM OVER()

SELECT *, 
    SumOfAmount = SUM(Amount) OVER(PARTITION BY ParentCo) 
FROM tbl 
+0

第二個問題可能是我的目的更好的問題。短而甜,很好,謝謝。 – fredolito

1

爲了讓您的第一個結果集,您還可以使用此查詢:

SELECT 
    ParentCo, 
    CASE WHEN GROUPING(Subsiduary) = 1 THEN '(all)' ELSE Subsiduary END AS Subsiduary, 
    SUM(Amount) AS SumOfAmount 
FROM 
    [table] 
GROUP BY 
    ParentCo, 
    ROLLUP(Subsiduary) 
ORDER BY 
    ParentCo, 
    Subsiduary