与有限的行和和

时间:2016-04-16 05:12:28

标签: sql postgresql

我想仅为每个用户和GROUP BY用户提供最后两周的总结。

我的表:

+----+------+--------+------+
| ID | User | Income | Week |
+----+------+--------+------+
| 1  | John | 50     | 1    |
+----+------+--------+------+
| 2  | John | 20     | 2    |
+----+------+--------+------+
| 3  | John | 25     | 3    |
+----+------+--------+------+
| 4  | John | 10     | 4    |
+----+------+--------+------+
| 5  | Mike | 45     | 1    |
+----+------+--------+------+
| 6  | Mike | 15     | 2    |
+----+------+--------+------+
| 7  | Mike | 10     | 3    |
+----+------+--------+------+
| 8  | Mike | 5      | 4    |
+----+------+--------+------+

期望的结果:

+------+--------+
| User | Income |
+------+--------+
| John | 35     |
+------+--------+
| Mike | 15     |
+------+--------+

正如您所看到的,我总结了每个用户的第4周和第3周,因为这些是过去2周。

提前致谢。

4 个答案:

答案 0 :(得分:2)

您可以使用row_number()来排序给定用户的前两周。此后,您可以汇总。适用于postgresql。

Select user, sum(income) 
from(
     select user, income, row_number() over (partition by user order by week desc) rn 
     from your_table
    ) 
where rn<3 group by user;

答案 1 :(得分:2)

的MySQL ---

SELECT User,Sum(Income) as Income
FROM mytable
WHERE week > (SELECT MAX(week) FROM mytable) - 2
GROUP BY User

sqlfiddle

的PostgreSQL ---

SELECT "user",Sum(Income) as Income
FROM mytable
WHERE week > (SELECT MAX(week) FROM mytable) - 2
GROUP BY "user"

sqlfiddle

答案 2 :(得分:0)

如果您使用的是mysql,请根据用户按行分组并按周编号的降序给出行号。然后按用户查找收入组合并且行号小于3。

<强>查询

SELECT t.User, SUM(t.Income) AS Income from(
    SELECT ID, User, Income, week,(
        CASE User WHEN @curA
        THEN @curRow := @curRow + 1
        ELSE @curRow := 1 AND @curA := User end
    ) + 1 AS row_num
    FROM my_table tbl,
    (SELECT @curRow := 0, @curA := '') r
    ORDER BY User, Week DESC
)t
WHERE t.row_num < 3
GROUP BY t.User

答案 3 :(得分:0)

假设您的表名为<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="icon-list icon-list-inline star-rating" id="star-rating"> <li class="selected"></li> <li class=""></li> <li class=""></li> <li class="selected"></li> <li class=""></li> </ul>,其字段为users

user, income, week

SELECT user AS User, SUM( income ) AS Income FROM users WHERE week > 2 GROUP BY user

如果您的周数是动态的,那么您可能需要计算where子句值。