I'm trying to get an order report returning not only a customers total number of orders, but also three additional fields, containing dates for first and last order, as well as the range (in days) between first and last order
The following query
SELECT customers.name,
customers.customer_id,
COUNT(orders.order_id) AS Orderscount
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.name,
customers.customer_id
HAVING Orderscount >= 2
ORDER BY Orderscount DESC
returns a table with name, customer_id and the count of total number of orders.
Question is, how can one add to this query to also get the date for the first_order, last_order and the date range between the two?
I'm using SQLite.
Use MIN
and MAX
to get first and last order date and julianday()
to calculate range:
SELECT customers.name,
customers.customer_id,
COUNT(orders.order_id) AS Orderscount,
MIN(col_name) AS firstOrder,
MAX(col_name) AS lastOrder,
ROUND(julianday(MAX(col_name)) - julianday(MIN(col_name))) AS range
FROM customers
JOIN orders ON customers.customer_id = orders.customer_id
GROUP BY customers.name,
customers.customer_id
HAVING Orderscount >= 2
ORDER BY Orderscount DESC
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.