SQL使用SUM和GROUPED两列

时间:2014-05-21 01:22:00

标签: 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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

你的意思是这样吗?

SELECT A, SUM(D)
FROM
(
    SELECT DISTINCT A, B, C, D
    FROM table
    WHERE C IN ('category 1','category 2')
) TEMP
GROUP BY A, B