列匹配的累积和

时间:2014-02-24 12:32:05

标签: mysql sql sum

我想做一个查询,给我一个累积的所有周数,但是以新月顺序呈现它们,如

Person | Week 1 | Week2 = Week1 + Week2 | Week 3 = Week 1 + 2 + 3|

我的表就像

ID | Week | Person | Item 1 | Item 2 | Item 3 | Iteration

周结果是所有项目的总和,迭代应该是本周的最高数字。

到目前为止,我已达到此目的,但结果并非预期,因为所有行的week1总和相等,这是错误的

SELECT person, w1sum, w2sum
FROM table AS t1, (

SELECT SUM( item1 + item2 + item3 ) AS w1sum
FROM table 
WHERE week =1
AND iteration
IN (

SELECT MAX( iteration ) 
FROM table
)
    GROUP BY person

) AS week1, 
(

SELECT SUM( item1 + item2 + item3 ) AS w2sum
FROM table 
WHERE week = 1 AND week = 2
AND iteration
IN (

SELECT MAX( iteration ) 
FROM table
)
    GROUP BY person

) AS week2

GROUP BY person

1 个答案:

答案 0 :(得分:2)

我认为你可以使用条件聚合做你想做的事情:

select person,
       sum(case when week in (1) then item1 + item2 + item3 else 0 end) as week1,
       sum(case when week in (1, 2) then item1 + item2 + item3 else 0 end) as week2
       sum(case when week in (1, 2, 3) then item1 + item2 + item3 else 0 end) as week3
from table t
where not exists (select 1
                  from table t2
                  where t2.person = t.person and
                        t2.week = t.week and
                        t2.iteration > t.iteration
                 )
group by person;

where子句获取每周每个人的最后一次迭代。