我正在尝试获取订单报告,不仅返回客户的订单总数,还包含三个附加字段,包含第一个和最后一个订单的日期,以及第一个和最后一个订单之间的范围(以天为单位)
以下查询
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
返回一个名称为customer_id的表格,以及订单总数。
问题是,如何添加到此查询中以获取first_order,last_order和两者之间的日期范围的日期?
我正在使用SQLite。
答案 0 :(得分:3)
使用MIN
和MAX
获取第一个和最后一个订单日期,使用julianday()
计算范围:
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