0

私は3つのテーブルを持つデータベースを持っています:

  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

ここで私が間違っていることを誰かが教えてくれたら、とても感謝しています。

4

1 に答える 1

1

二重結合は、すべてのtemp_subがすべてのtemp_orderに対して繰り返されることを意味します。二重カウントを回避する1つの方法はdistinct、一意の列にを追加することです。テーブルにと呼ばれる主キーがある場合、次のidようになります。

SELECT monthlist.name 'Month'
  ,count(distinct temp_subs.id) 'Expiry Date'
  ,count(distinct temp_orders.id) 'Order Date'  
于 2012-08-27T12:06:37.777 に答える