mysql - 两列使用 SUM 和 GROUPED 的 SQL

标签 mysql sql

我有以下示例表:

enter image description here

我需要编写一个执行以下操作的查询:

A. SUMS column D for category 1 and category 2 (note the duplicates; 
I only need one row from each category.

B. GROUP BY column B and column A - The output for each row will look as follows:

Customer 1        (SUM(category 1 and 2 for customer 1(without duplicates))

Customer 2        (SUM(category 1 and 2 for customer 2(without duplicates))

Customer 3        (SUM(category 1 and 2 for customer 3(without duplicates))

我正在使用以下查询/子查询,但我不知道如何按两列进行分组,以便显示 SUM 和相关客户:

SELECT SUM(col_d) AS total_growth FROM (SELECT col_d from table       WHERE 
account_manager_id = '159795'        GROUP BY col_c) as total LIMIT 0, 1000

最佳答案

SELECT SUM(DISTINCT col_d) 
FROM table 
WHERE category IN ('category 1','category 2') AND account_manager_id = '159795'
GROUP BY customer
LIMIT 0, 1000

关于mysql - 两列使用 SUM 和 GROUPED 的 SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23772516/

相关文章:

mysql - 过程中的相同 Select 语句返回所有行

java - HIbernate 标准生成器与 if 条件求和

MySQL 在一个查询中对不同表进行多次计数

mysql - 如何使用具有多个输入的表单更新 mysql 记录,但仅使用输入的值更新输入

php - 选择一个不同的值计数及其自身的值 1 查询

php - 当函数以数组形式返回时迭代记录集

sql - 在 mysql 中选择使用计数

SQL 案例语句

sql - 为什么 LTRIM 函数没有返回预期结果

mysql - Django 完整性错误 - id 不能为空