减去同一列的值

时间:2014-07-28 17:01:29

标签: sql sqlite

我试图按日期desc减去重量列顺序的值,所以我可以得到它们之间的差异,例如:

重量值:90-93-94-97

所需输出:0-3-1-3

90-90 | 93-90 | 94-93 | 97-94

2 个答案:

答案 0 :(得分:1)

SQL Lite不支持运行总计或累计总计。但你可以计算它的方式

假设以下表格:tb_usertb_weight

|------------------|    |----------------------|
|   Id   | Name    |    |UserId| Date  | Weight|
|------------------|    |----------------------|
|   U1   | John    |    |  U1  | 1-Jan | 90    |
|   U2   | Jill    |    |  U2  | 2-Jan | 93    |
|------------------|    |  U1  | 3-Jan | 94    |
                        |  U2  | 4-Jan | 97    |
                        |----------------------|


    SELECT user.name, 
           current.date, 
           current.weight, 
           current.weight - (SELECT previous.weight -- select weight on the previous day available
                               FROM tb_weight previous
                              WHERE previous.date < current.date
                                AND previous.userId = user.id
                           ORDER BY previous.date DESC
                              LIMIT 1) -- select the top 1 record
    FROM tb_weight current
  INNER JOIN tb_user users ON (users.id = current.UserId)
      ORDER BY current.date DESC

22SEP2014更新:根据要求添加了与用户表的连接

答案 1 :(得分:1)

这是一个连接到前一行的行的查询(第一个权重行除外,它自行减去)

select x.date, x.weight, x.weight - coalesce(y.weight, x.weight) delta
from (
  select w.date, w.weight, max(d.date) previous
  from weights w
  left join weights d on d.date < w.date
  group by w.date, w.weight) x
left join weights y on y.date = previous
order by x.date

使用数据查看SQLFiddle

2014-01-01 90
2014-01-02 93
2014-01-03 94
2014-01-04 94
2014-01-05 93
2014-01-06 97

并产生输出:

date        weight  delta
2014-01-01  90      0
2014-01-02  93      3
2014-01-03  94      1
2014-01-04  94      0
2014-01-05  93      -1
2014-01-06  97      4