2016-02-09 103 views
0

我想生成一個報告來按月統計訂單數和訂單數。訂單和訂單行數報告

orders表我已經order_idorder_date領域

order_lines表,我有order_lines_idorder_id

我希望報表生成這樣的:

Year, Month, NumberOfOrders, NumbersOfLines 
2015 1   4    55 
2015 2   3    6 

我有嘗試了下面的SQL,並沒有工作我怎麼想成爲

SELECT 
    Year(orders.order_date) as Year, 
    Month(orders.order_date) as Month, 
    count(orders.order_id) as NumberOfOrders, 
    count(order_lines.order_lines_id) as NumbersOfLines, 
FROM `orders`    
    LEFT JOIN order_lines On order_lines.orders_id = order_lines.order_lines_id 
group by sales.sales_id, order_lines.order_lines_id 

回答

1

由於兩個原因,它不起作用,1 - 因爲您用錯誤的值對它進行分組。考慮一下,你想每年,每月彙總一次。你爲什麼按照salesid和orderlines id進行分組?

以及2-你的左邊是不正確的,你需要的公共列在這種情況下是order_id

反正兩個表中比較連接條件,試試這個:

SELECT 
    Year(t.order_date) as Year, 
    Month(t.order_date) as Month, 
    count(distinct t.order_id) as NumberOfOrders, 
    count(order_lines.order_lines_id) as NumbersOfLines, 
FROM `orders` t    
    LEFT JOIN order_lines On t.order_id = order_lines.order_id 
group by Year(t.order_date), Month(t.order_date) 

或相關查詢:

SELECT 
    Year(t.order_date) as Year, 
    Month(t.order_date) as Month, 
    (select count(distinct s.order_id) 
     from orders s 
     where Year(t.order_date) = Year(s.order_date) 
     and Month(t.order_date) = Month(s.order_date)) as NumberOfOrders, 
    count(order_lines.order_lines_id) as NumbersOfLines, 
FROM `orders` t    
    LEFT JOIN order_lines On t.order_id = order_lines.order_id 
group by Year(t.order_date), Month(t.order_date) 
+0

快如箭! +1 –

+1

@JorgeCampos謝謝..誰降低價格,爲什麼? – sagi

+0

任何人都可以解釋爲什麼我用正確的答案兩次downvoted? – sagi