2014-02-24 93 views
0

我想打一個查詢,讓我對所有周累計相加,而是會呈現新月形爲了像累計總和,其中列匹配

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 

回答

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條款得到最後的重複中的每個人每個星期。

+0

太棒了!謝謝! –