2016-02-27 425 views
1

我試圖得到一份訂單報告,不僅返回客戶訂單總數,還返回三個附加字段,其中包含第一個和最後一個訂單的日期以及範圍第一個和最後爲了訂單日期範圍內的SQL客戶訂單查詢

下面的查詢

之間

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。

回答

3

使用MINMAX獲得第一和最後訂購日期和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 
+0

這工作非常出色。範圍出現爲一個分數'天'的數字。我將如何將它整數到一個整數? (我將col_name更改爲我的purchase_date字段) –

+1

@TotteKarlsson將「ROUND」添加到最近的整數。 – lad2025

+0

@TotteKarlsson或'CAST(... AS INT)'截斷小數部分 – lad2025