MySql通过其他列上的不同初始值聚合

时间:2017-09-29 21:23:36

标签: mysql sql

我有一个表结构如下

| user_id | value | date       |
|---------|-------|------------|
| 1       | 5     | 2017-09-01 |
| 2       | 6     | 2017-09-01 |
| 1       | 1     | 2017-09-02 |
| 1       | 2     | 2017-09-03 |
| 2       | 9     | 2017-09-02 |
| 1       | 3     | 2017-09-04 |
| 2       | 5     | 2017-09-04 |
| 2       | 5     | 2017-09-05 |
| 1       | 1     | 2017-09-05 |
| 1       | 5     | 2017-09-06 |
| 1       | 6     | 2017-09-07 |
| 1       | 3     | 2017-09-08 |
| 1       | 4     | 2017-09-09 |
| 2       | 6     | 2017-09-06 |
| 1       | 1     | 2017-09-10 |

我有另一个表格,其中给出了user_id的初始截止日期,如

| user_id | date       |
|---------|------------|
| 1       | 2017-09-04 |
| 2       | 2017-09-05 |

所有用户的最终截止日期为2017-09-08

我想得到user_id

汇总的值之和

我试过的是

SELECT user_id, SUM(value) as Total 
FROM table 
WHERE date >= $DATE and date <= '2017-09-08'
GROUP BY user_id

我遇到了如何处理$ DATE,因为它是每个用户的变量

案例中的解决方案应该是

| user_id | Total      |
|---------|------------|
| 1       | 18         |
| 2       | 11         |

3 个答案:

答案 0 :(得分:3)

假设您的表名为userscutoffcutoff具有每个用户的截止日期。试试这个,让我知道它是否有效。

select u.user_id,sum(u.value) Total 
from users u join cutoff c on u.user_id=c.user_id and (u.date>=c.date and u.date<='2017-09-08') 
group by u.user_id

答案 1 :(得分:2)

SELECT x.user_id, SUM(x.value) as Total 
FROM table x 
WHERE x.date >= (select date from table2 where user_id = x.user_id) 
and x.date <= '2017-09-08'
GROUP BY x.user_id

答案 2 :(得分:1)

使用存在的地方

SELECT a.user_id, SUM(a.value) as Total 
FROM table1 a
WHERE EXISTS (
  SELECT 1
  FROM table2 b
  WHERE a.user_id = b.user_id 
  AND a.date >= b.date and a.date <= '2017-09-08'
)
GROUP BY user_id

DEMO

使用条件聚合

SELECT a.user_id,
SUM(CASE WHEN a.date >= b.date and a.date <= '2017-09-08' 
    THEN a.value 
    ELSE 0 
    END) as Total 
FROM table1 a
JOIN table2 b ON a.user_id = b.user_id
GROUP BY user_id

DEMO