MySQL:聚合计数

标签 mysql sql select count aggregate

我试图找出有多少公司在特定分割市场中有销售额。我已经设法统计了销售条目 (5),但我似乎也无法按产品分割进行汇总。请看这个简化:

http://sqlfiddle.com/#!9/685cb/1

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

INSERT INTO Table1
    (`company`, `segment`, `sales`)
VALUES
    ('ACME',10,100),
    ('ACME',11,100),
    ('HAL',10,25),
    ('HAL',13,25),
    ('GEN',11,50)
;

SELECT COUNT(company) AS companies,
CASE 
    WHEN segment IN (10, 11, 12, 13, 14, 15, 16)
    THEN 'Product segment A'
    WHEN segment IN (20, 21, 22)
    THEN 'Product segment B'
    WHEN segment IN (30)
    THEN 'Product segment C'
    END AS grp, SUM(sales) AS sum_sales
FROM Table1
WHERE
       (company LIKE '%ACME%'
     OR company LIKE '%HAL%'
     OR company LIKE '%GEN%'
    )
AND
    segment IN (10, 11, 12, 13, 14, 15 ,16, 20, 21, 22, 30)
GROUP BY grp
ORDER BY grp
;

目标是让“公司”显示 3,因为在分割市场 A 中有 3 家公司有销售额。

最佳答案

您可以在 count 函数中使用 distinct 修饰符来获取不同 条目的数量:

SELECT COUNT(DISTINCT company) AS companies,
-- Here -----^
CASE 
    WHEN segment IN (10, 11, 12, 13, 14, 15, 16)
    THEN 'Product segment A'
    WHEN segment IN (20, 21, 22)
    THEN 'Product segment B'
    WHEN segment IN (30)
    THEN 'Product segment C'
    END AS grp, SUM(sales) AS sum_sales
FROM Table1
WHERE
       (company LIKE '%ACME%'
     OR company LIKE '%HAL%'
     OR company LIKE '%GEN%'
    )
AND
    segment IN (10, 11, 12, 13, 14, 15 ,16, 20, 21, 22, 30)
GROUP BY grp
ORDER BY grp
;

SQLFiddle

关于MySQL:聚合计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43842615/

相关文章:

SQL DISTINCT 位于 select 中间

mysql - 如何编写一个 SQL 查询来给出某个值在表中重复的次数?

mysql - 将图像直接存储在数据库中还是作为base64数据存储?

mysql - 如果没有在 my.cnf 中指定,innodb_data_file_path 的默认设置是什么?

sql - 如何在多个列中查找重复计数?

Oracle SELECT 查询 : collapsing null values when pairing up dates

sql - 如何在 T-SQL 中计算 ABCIndicator

php - 如何在php中提取二维码内容并将其存储为数组?

sql - 根据电话号码计算人的时区(GMT 偏移量)?

sql - PostgreSQL SSPI 身份验证 - fatal error : 2801: password authentication failed for user "xxx"