如何在MySQL中基于多分组对单个列求和

时间:2016-03-01 18:37:10

标签: mysql

我有两个表一个是Sales,另一个是BrandMaster

我的要求:如何根据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' SNo'。我需要每个产品和多产品的销售额总和。请帮助我。

参考文章:How to Sum a single Column based on grouping in MySQL

1 个答案:

答案 0 :(得分: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