2016-03-01 37 views
-2

我有一個兩個表一個是銷售,另一種是BrandMaster如何基於多分組總結單個列在MySQL

我的要求:如何基於多組總之單個列MySQL的

銷售表的結構和數據:

SNo   BID   Amount 
----------------------------------- 
101    1   200 
102    2   500 
103    5   800 
104    8   250 
105    1   200 
106    2   500 
107    5   800 
108    8   250 

BrandMaster的數據結構和表:

BID   BrandName   
------------------------- 
1    Prod#1 
2    Prod#2 
3    Prod#3 
4    Prod#4 
5    Prod#5 
6    Prod#6 
7    Prod#7 
8    Prod#8 

我的期望輸出:

BrandName   SumAmount   
------------------------- 
Prod#1     400 
Prod#2 and Prod#3  500 
Prod#4     0 
Prod#5     0 
Prod#6 and Prod#8  2100 
Prod#7     0 

銷售表包含BrandID 'BID' 和銷售金額與銷售ID '斯諾'。我需要每種產品和多種產品的銷售金額總和。請幫助我。

基準柱:How to Sum a single Column based on grouping in MySQL

+1

東西,所以爲什麼'督促#2'和'督促#3'在一起嗎?是否在其他地方分組信息? –

回答

1

你可能需要用CASE

SELECT * 
FROM Sales S 
JOIN BrandMaster B 
    ON S.`BID` = B.`BID` 
GROUP BY CASE WHEN `BrandName` = 'Prod-1' THEN 'Prod-1' 
       WHEN `BrandName` = 'Prod-2' 
       OR `BrandName` = 'Prod-3' THEN 'Prod-2 & Prod-3' 
       WHEN `BrandName` = 'Prod-4' THEN 'Prod-4' 
       WHEN `BrandName` = 'Prod-5' THEN 'Prod-5' 
       WHEN `BrandName` = 'Prod-6'    
       OR `BrandName` = 'Prod-8' THEN 'Prod-6 & Prod-8' 
       WHEN `BrandName` = 'Prod-7' THEN 'Prod-7' 
      END