具有内部查询的mysql中的Sum函数

时间:2016-06-10 14:40:59

标签: mysql sql sql-server subquery

我有如下查询:

    select b.*, SUM(h.points) as points
    from brands b left join
    histories h
    on b.id = h.brandid and h.userId = $userId
    where b.id=$brandId and b.active=1 
    group by b.id
    limit 1

我想仅为以下案例加分:

where h.type != 10, h.points !=0 and points should be between two dates like this: h.time between '2016-06-01' and '2016-06-31'...

我认为这可以通过使用子查询来完成,但我不确定如何...你能帮助我的人吗?

所需的输出是:

userId  brandId  points 

1         64      155

1         15      100

依此类推,我为每个用户提供了很好的总结点,这些用户在两个日期之间得分,并且点的类型不是!= 10;

表结构如下:

Brands => Histories <= Users

1 个答案:

答案 0 :(得分:3)

select b.id, 
sum(case when h.type <> 10 and h.time between '2016-06-01' and '2016-06-31' then h.points 
    else 0 end) as points
from brands b 
left join histories h on b.id = h.brandid and h.userId = $userId
and b.active=1 and b.id=$brandId
group by b.id