NBC
NBC

Reputation: 1698

SQL Sum Columns

I want to get the following output:

Main table:

Email       | Group | id
[email protected] | Y     | 1
[email protected] | Y     | 2 
[email protected] | N     | 3
[email protected] | N     | 4

Join Table:

Email       | Value
[email protected] | 10
[email protected] | 20
[email protected] | 30

Desired result (only take the [email protected] value once, despite appearing in the first table twice):

Group  | Email Count | Sum
Y      | 1           | 10
N      | 2           | 50

Here is the sqlfiddle I've been playing around with: http://sqlfiddle.com/#!9/c2a24d/8

Upvotes: 1

Views: 43

Answers (2)

Ethilium
Ethilium

Reputation: 1234

You were close in your SQLFiddle. You just needed to join on a distinct select.

SELECT  
e.Unsub as Unsub,
count(e.email) as EmailCount,
sum(c.sum) as EmailSum
FROM CountTable c
JOIN (select distinct email, Unsub from EmailsTable) e on c.email = e.email
GROUP BY e.unsub

SQLFiddle

Upvotes: 1

Juan Carlos Oropeza
Juan Carlos Oropeza

Reputation: 48197

First remove the duplicates, and then do the calculations

SQL DEMO

SELECT filter.`Unsub`, COUNT(*),  SUM(`sum`)
FROM (
        SELECT DISTINCT `Unsub`, `email` 
        FROM EmailsTable ) as filter
JOIN  CountTable    
  ON filter.`email` = CountTable.`email` 
GROUP BY  filter.`Unsub`

OUTPUT

| Unsub | COUNT(*) | SUM(`sum`) |
|-------|----------|------------|
|     N |        2 |         50 |
|     Y |        1 |         10 |

Upvotes: 1

Related Questions