SQL聚合组

时间:2017-01-02 13:45:26

标签: mysql sql grouping

我觉得这是一个愚蠢的问题,但我无法通过搜索找到解决方案。我有一个包含销售数据的数据集,我想将一些ID组组合在一起并显示销售总额。我不关心个别物品,我只想看到物品组和销售总额。

我现在正在做的简化版本是:

SELECT year, quarter, company, segment, sum(sales) AS total_sales
FROM table
WHERE segment = 001 OR segment = 015
AND producer LIKE '%ACME Inc.%'
AND year = 2015 OR year = 2016
GROUP BY quarter, year, producer, segment
ORDER BY year, quarter, producer, segment ASC
;

我的主要问题是将段001和015放入同一组,例如“Jelly'以便输出显示

year|quarter|company|segment|total_sales

2015|1|ACME Inc.|Jelly|100

Jelly'包括段001和015。

我能够列出单个项目,但不能将它们分组在聚合组中。我的问题是只能过滤我想要查看的公司,只能过滤我想要查看的细分,同时我会创建和列出细分的自定义组。

感谢您的帮助:)

编辑:MCVE - http://sqlfiddle.com/#!9/2414bd/3

CREATE TABLE Table1
    (`company` text, `sales` int, `year` int, `quarter` int,
     `segment` text)
;

INSERT INTO Table1
    (`year`, `quarter`, `company`, `segment`, `sales`)
VALUES
    (2015,1,'ACME',001,100),
    (2015,1,'ACME',015,100),
    (2015,1,'HAL',001,25),
    (2015,1,'HAL',015,25),
    (2015,1,'ACME',002,50),
    (2015,1,'HAL',003,50)
/*many other companies and segments as well*/
;

2 个答案:

答案 0 :(得分:1)

首先,我认为你需要修复你的where条款。以0开头的数字通常是字符串。另外,您应该使用in并谨慎对待and / or逻辑:

SELECT year, quarter, company, segment, sum(sales) AS total_sales
FROM table
WHERE segment IN ('001', '015') AND
      producer LIKE '%ACME Inc.%' AND
      year IN (2015, 2016)
GROUP BY quarter, year, producer, segment
ORDER BY year, quarter, producer, segment ASC;

接下来,如果要组合细分,请使用case。你似乎想要:

SELECT year, quarter, company, 'Jelly' as segement,
       SUM(sales) AS total_sales
FROM table
WHERE segment IN ('001', '015') AND
      producer LIKE '%ACME Inc.%' AND
      year IN (2015, 2016)
GROUP BY quarter, year, producer
ORDER BY year, quarter, producer ASC;

答案 1 :(得分:0)

SELECT year, quarter, company,
CASE
  WHEN segment IN (001,015)
  THEN 'Jelly'
  WHEN segment IN (002,003)
  THEN 'Bread' ELSE segment END segment,
SUM(sales) AS total_sales
FROM Table1
WHERE company LIKE '%ACME%' OR company LIKE '%HAL%'
AND year IN (2015,2016)
GROUP 
   BY year
    , quarter
    , company
    , CASE WHEN segment IN (001,015) THEN 'Jelly'
           WHEN segment IN (002,003) THEN 'Bread' 
           ELSE segment
           END
 ORDER 
    BY year, quarter, company, segment ASC
;