2012-08-27 134 views
0

我有3個表數據庫:SQL查詢到組日期按月

  1. mothlist([number],[name])
  2. temp_subs([sub_id],[date_created],[expiry_date])
  3. temp_orders([order_id],[sub_id],[order_date])

我想編寫一個查詢來獲得總統計當月按月分組的到期日和訂單。

查詢我現在是:

SELECT 
    monthlist.name 'Month', 
    count(temp_subs.expiry_date) 'Expiry Date', 
    count(temp_orders.order_date) 'Order Date'  
FROM 
    monthlist 
    FULL JOIN temp_subs 
    on 
     monthlist.number = datepart(month, temp_subs.expiry_date) and 
     datepart(year, temp_subs.expiry_date) = year(getdate()) 
    FULL JOIN temp_orders 
    on 
     monthlist.number = datepart(month, temp_orders.order_date) and 
     datepart(year, temp_orders.order_date) = year(getdate()) 
GROUP BY monthlist.number ,monthlist.name  
ORDER BY monthlist.number 

如果有人能告訴我我是什麼洞錯在這裏我將非常感激。

+1

現在出現了什麼問題?行數太多? – gbn

+0

你得到什麼錯誤? – SuganR

回答

1

雙連接意味着每個temp_sub對每個temp_order都重複。避免重複計算的一種方法是在唯一列上添加distinct。如果表格有一個名爲id的主鍵,則可能如下所示:

SELECT monthlist.name 'Month' 
    ,count(distinct temp_subs.id) 'Expiry Date' 
    ,count(distinct temp_orders.id) 'Order Date' 
+0

感謝Andomar爲您提供快速回復,但添加'distinct'不起作用。如果我做了一個LEFT JOIN而不是全部,只留下其中一個,那麼總數是正確的。現在我試圖找到一種方法來同時加入 – minbor

+0

你必須在獨特的列上添加'distinct',比如'id'。然後它會工作。 – Andomar

+0

謝謝。不同的ID字段和左連接完美地工作 – minbor