获取一个列,显示每个不同日期的操作索引



我有一个表,存储不同日期的操作。是否有可能得到一个列,显示每一个不同的日子的操作索引?

这是我的表:

id    date          sum
 1    2014-01-03    -31.00
 2    2014-01-03    +21.21
 4    2014-01-03    - 2.90
 5    2014-01-12    +10.00
 6    2014-01-18    -18.93
 8    2014-01-24    - 4.38
11    2014-01-24    - 6.00

这是我的查询应该显示的内容:

id    date          sum       index
 1    2014-01-03    -31.00        1  -- first operation on the 2014-01-03
 2    2014-01-03    +21.21        2  -- second operation on the 2014-01-03
 4    2014-01-03    - 2.90        3  -- etc...
 5    2014-01-12    +10.00        1
 6    2014-01-18    -18.93        1
 8    2014-01-24    - 4.38        1
11    2014-01-24    - 6.00        2

对于其他DBMS,这将非常容易使用窗口函数。但是SQLite不支持它们,所以你需要使用一个相关的子查询,这使得它非常慢:

select t1.id, 
       t1.date, 
       t1.sum, 
       (select count(*) from the_table t2 where t2.date = t1.date and t2.id <= t1.id) as idx
from the_table t1
order by date, id;

但是正如我说的:这个将是缓慢的!


Btw: date是一个可怕的列名。首先,它也是一个保留字,但更重要的是,它没有记录列存储的内容。订单日期?截止日期?预产期?…

最新更新