SQL Sum列

时间:2017-03-22 00:01:17

标签: sql

我想获得以下输出:

主表:

Email       | Group | id
a@gmail.com | Y     | 1
a@gmail.com | Y     | 2 
b@gmail.com | N     | 3
c@gmail.com | N     | 4

加入表:

Email       | Value
a@gmail.com | 10
b@gmail.com | 20
c@gmail.com | 30

期望的结果(尽管在第一个表中出现两次,但只取a@gmail.com值一次):

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

这是我一直在玩的sqlfiddle: http://sqlfiddle.com/#!9/c2a24d/8

2 个答案:

答案 0 :(得分:1)

你在SQ​​LFiddle中很近。你只需加入一个独特的选择。

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

答案 1 :(得分:1)

首先删除重复项,然后进行计算

<强> 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`

<强>输出

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