如何根据时间戳查询每个记录的索引

时间:2019-03-04 03:26:29

标签: mysql sql

我有一个订单表,我想索引每个公司的第一,第二,第三...等订单。

表格示例

|---------------------|--------------------------|
|      company_id     |     created_at           |
|---------------------|--------------------------|
|          1          |   2019-01-01 01:00:00    |
|---------------------|--------------------------|
|          1          |   2019-02-01 01:00:00    |
|---------------------|--------------------------|
|          2          |   2019-03-01 02:00:00    |
|---------------------|--------------------------|
|          3          |   2019-03-01 08:30:00    |
|---------------------|--------------------------|
|          2          |   2019-03-01 10:00:00    |
|---------------------|--------------------------|

最后我会被这样询问吗?但我不确定如何.....我一直回到计数和分组字段,但我似乎无法根据时间戳获取每一行的总和

|---------------------|--------------------------|-------|
|      company_id     |     created_at           |count()|
|---------------------|--------------------------|--------
|          1          |   2019-01-01 01:00:00    |   1   |
|---------------------|--------------------------|--------
|          1          |   2019-02-01 01:00:00    |   2   |
|---------------------|--------------------------|--------
|          2          |   2019-03-01 02:00:00    |   1   |
|---------------------|--------------------------|--------
|          3          |   2019-03-01 08:30:00    |   1   |
|---------------------|--------------------------|--------
|          2          |   2019-03-01 10:00:00    |   2   |
|---------------------|--------------------------|--------

2 个答案:

答案 0 :(得分:2)

SELECT 
    @row_number:=CASE
        WHEN @company_id = company_id THEN @row_number + 1
        ELSE 1
    END AS count1,
    @company_id:=company_id as company_id,
    created_at
FROM
    Table1,(SELECT @company_id:=0,@row_number:=0) as t
ORDER BY company_id;

SQL Fiddle

答案 1 :(得分:0)

最后我的解决方法如下,这似乎比上面的建议更简单。

SELECT company_id
,(
    SELECT count(*) + 1
    FROM ORDERS AS orderCount
    WHERE orderCount.company_id = orders.company_id
        AND orderCount.created_at < orders.created_at
    ) AS order_count
FROM ORDERS
ORDER BY created_at