SQL Query按月分组日期

时间:2012-08-27 12:02:04

标签: sql sql-server-2008

我有一个包含3个表的数据库:

  1. mothlist([number],[name])
  2. temp_subs([sub_id],[date_created],[expiry_date])
  3. temp_orders([order_id],[sub_id],[order_date])
  4. 我正在尝试编写一个查询来获取按月分组的当前年份的总计数到期日期和订单。

    我现在的查询是:

    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 个答案:

答案 0 :(得分:1)

双连接意味着每个temp_sub都会重复每个temp_sub。避免重复计算的一种方法是在唯一列上添加distinct。如果表中有一个名为id的主键,则可能如下所示:

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