DataGuy
DataGuy

Reputation: 1725

SQL using SUM and GROUPED by two columns

I have the following sample table:

enter image description here

And I need to write a query that does the following:

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))

I am using the following query/sub-query, but I dint know how to group by both columns so the SUM and the related customer will show:

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

Upvotes: 1

Views: 69

Answers (2)

Leo Zhao
Leo Zhao

Reputation: 544

Do you mean like this?

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

Upvotes: 0

potashin
potashin

Reputation: 44581

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

Upvotes: 1

Related Questions