简体   繁体   中英

SQL - How can I count days by comparing current row to the 1st row?

I have a table as below in the database, how can I write a SQL to show the expected result?

  • first_date: the first order_date on the table ORDER BY order_date ASC
  • days_to_date: (order_date - first_date) in number of days

My table:

id | order_date | order_ref
---+------------------------
 1 | 2015-03-01 | BC101
 2 | 2015-03-01 | BC102
 3 | 2015-03-02 | BC103
 4 | 2015-03-03 | BC104

Expected result:

id | order_date | first_date | days_to_date
---+------------+------------+-------------
 1 | 2015-03-01 | 2015-03-01 | 0
 2 | 2015-03-01 | 2015-03-01 | 0
 3 | 2015-03-02 | 2015-03-01 | 1
 4 | 2015-03-03 | 2015-03-01 | 2

Other notes:

  • I'm using HSQLDB 2.0.0, but prefer solving the problem of getting the first_date displayed on every row in general cases if that's possible

Thanks in advance

Try

select id, order_date, 
      (select min(order_date) from your_table) as first_date,
      datediff('day', (select min(order_date) from your_table), order_date) as days_to_date
from your_table
order by order_date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM