比较当前与上周的计数值

时间:2016-08-15 14:22:35

标签: mysql

我不确定我的标题是否正确,但我认为订单存在问题。

我根据total计算特定name的{​​{1}}值:

week

ID | name | week | total ======================== 1 | Foo | 9 | 2 2 | Bar | 9 | 4 3 | Lou | 9 | 3 4 | Zoo | 9 | 5 ... 21 | Foo | 10 | 10 22 | Bar | 10 | 12 23 | Lou | 10 | 14 24 | Zoo | 10 | 16 ... 45 | Foo | 11 | 16 46 | Bar | 11 | 12 48 | Lou | 11 | 24 49 | Zoo | 11 | 24 的{​​{1}}总是大于或等于它的前辈。

我想像这样得到最后一次 total的计数:

week

这就是我目前所拥有的,但它总是从表中返回第一个可用的

week

另外,我想获得一个包含所有周及其name | week | count =================== Foo | 11 | 6 //= 16-10 Bar | 11 | 0 //= 12-12 Lou | 11 | 10 //= 24-14 Zoo | 11 | 8 //= 24-18

值的列表

1 个答案:

答案 0 :(得分:1)

在查询中添加where子句,以便定义周

SELECT current.name, current.week, current.count - last.count
FROM table as current 
JOIN table as last
ON current.name = last.name
AND current.week = last.week - 1
WHERE current.week = 11

如果您想要所有周的结果,我会使用子选择:

SELECT current.name, current.week, current.count,
   current.count - (SELECT last.count FROM table as last WHERE last.name = current.name AND last.week = current.week-1) as diff
FROM table as current