2013-04-30 63 views
0

表5:經理的MySQL:檢索基於表2中值表3的結果標記,以表1

id | name 
1 | Steve 
2 | Jacob 

表4:deputy_managers

id | manager_id | name 
1 | 2 | Mary 
2 | 2 | Linda 
3 | 1 | Nathan 

表3:team_leads

id | deputy_manager_id | name 
1 | 3 | Stephen 
2 | 1 | Patrick 
3 | 2 | Tony 
4 | 1 | Austin 

表2:sales_executives

id | team_lead_id | name 
1 | 1 | Johnny 
2 | 3 | Dalton 
3 | 4 | Sonora 
4 | 2 | Jessie 

表1:銷售

id | sales_executive_id | product | quantity 
1 | 3 | product1 | 10 
2 | 2 | product3 | 6 
3 | 3 | product2 | 5 
4 | 1 | product1 | 4 

隨着銷售表中提供的數據,我想寫MySQL查詢獲取銷售的產品的總量:

  1. 從經理史蒂夫的團隊。
  2. 從副經理瑪麗的團隊。
  3. 從團隊領導Tony的團隊。

請幫忙。

在此先感謝。

回答

0
  1. 從經理史蒂夫的團隊

    SELECT product, SUM(quantity) 
    FROM  managers   m 
        JOIN deputy_managers d ON d.manager_id   = m.id 
        JOIN team_leads  t ON t.deputy_manager_id = d.id 
        JOIN sales_executives e ON e.team_lead_id  = t.id 
        JOIN sales   s ON s.sales_executive_id = e.id 
    WHERE m.name = 'Steve' 
    GROUP BY product 
    
  2. 從副經理瑪麗的團隊

    SELECT product, SUM(quantity) 
    FROM  deputy_managers d 
        JOIN team_leads  t ON t.deputy_manager_id = d.id 
        JOIN sales_executives e ON e.team_lead_id  = t.id 
        JOIN sales   s ON s.sales_executive_id = e.id 
    WHERE d.name = 'Mary' 
    GROUP BY product 
    
  3. 從團隊領導託尼的團隊

    SELECT product, SUM(quantity) 
    FROM  team_leads  t 
        JOIN sales_executives e ON e.team_lead_id  = t.id 
        JOIN sales   s ON s.sales_executive_id = e.id 
    WHERE t.name = 'Tony' 
    GROUP BY product 
    

請在sqlfiddle上查看。

+0

eggyal,完美的作品!非常感謝!這給我帶來了很大的壓力。再次感謝!! – 2013-04-30 13:40:20

相關問題