2015-02-11 60 views
1

我想要一個查詢,其中數據按reseller_id分組,其中parent_res_id = 0。所有其他行應使用parent_res_id而不是reseller_id按兩個不同列的SQL查詢分組

例如,parent_res_id 0(管理帳戶)產生了兩個reseller_id:1和2.他們每個人創建了另一個分銷商(分別爲3和4)。我想與他們的父母子女組行,所以reseller_id 3行添加到1和reseller_id 4行添加到2基本上它是深度的樹1

表:

duration call_charge reseller_id parent_res_id 
2    1    1   0 
3    2    2   0 
4    3    3   1 
5    4    4   2 
6    5    5   1 
7    6    6   5 

期望的結果:

sum(duration) sum(call_charege) reseller_id 
19     15     1 
8     6     2 
+0

有沒有人明白這一點? – 2015-02-11 10:51:30

+1

@CoderofCode:我想我是。 *只有*必須讀取它像5次... – 2015-02-11 11:05:04

+1

還有兩個'RDBMS'你也可以標記這個 – 2015-02-11 11:05:57

回答

2

隨着UNION ALL

SELECT reseller_id, sum(duration) AS sum_dur, sum(call_charge) AS sum_char 
FROM (
    SELECT reseller_id, duration, call_charge 
    FROM tbl 
    WHERE parent_res_id = 0 

    UNION ALL 
    SELECT parent_res_id, duration, call_charge 
    FROM tbl 
    WHERE parent_res_id <> 0 
    ) sub 
GROUP BY 1; 

替代用CASE表達式:

SELECT CASE WHEN parent_res_id = 0 
      THEN reseller_id 
      ELSE parent_res_id 
     END AS reseller_id 
    , sum(duration) AS sum_dur, sum(call_charge) AS sum_char 
FROM tbl 
GROUP BY 1; 

相同的結果。可能更快,因爲它只需要一次表掃描。

對於深度大於1或2的樹木,遞歸CTE是正確的技術。例如:

+0

upvote爲理解的問題。 – 2015-02-11 11:06:23

+0

抱歉無法向我自己解釋,但我希望如果管理員創建了兩個分銷商讓我們說reseller1和reseller2然後parent_res_id他們兩個將'0'和reseller_id將分別爲'1'和'2'。現在經銷商1創建的是自己的經銷商讓我們說reseller3然後parent_res_id爲他將'1'和經銷商id將'3'現在我想要的結果將有兩個經銷商,這是由admin創建的是reseller1和reseller2但數據reseller3將被添加到reseller1中,因爲reseller1創建了它。 – 2015-02-11 11:17:45

+0

@AshokBarthwal:我想我理解了這一點,我的查詢實現了你所要求的。根據需要結果。我添加了一個替代查詢,並冒昧地在這個問題中重寫你的解釋。 – 2015-02-11 11:43:06

0

將它與其他樣本數據的工作告訴我?

;WITH CTE 
AS (
    SELECT 2 duration 
     ,1 call_charge 
     ,1 reseller_id 
     ,0 parent_res_id 

    UNION ALL 

    SELECT 3 
     ,2 
     ,2 
     ,0 

    UNION ALL 

    SELECT 4 
     ,3 
     ,3 
     ,1 

    UNION ALL 

    SELECT 5 
     ,4 
     ,4 
     ,2 
    ) 
    ,CTE1 
AS (
    SELECT reseller_id 
     ,duration 
     ,call_charge 
     ,parent_res_id 
    FROM cte 
    WHERE parent_res_id = 0 

    UNION ALL 

    SELECT b.reseller_id 
     ,a.duration + b.duration 
     ,a.call_charge + b.call_charge 
     ,a.parent_res_id 
    FROM cte a 
    INNER JOIN cte1 b ON a.parent_res_id = b.reseller_id 
    WHERE b.parent_res_id = 0 
    ) 
SELECT reseller_id 
    ,duration [sum(duration)] 
    ,call_charge [sum(call_charege)] 
FROM cte1 
WHERE parent_res_id > 0 
ORDER BY reseller_id