次の列を持つテーブルProductがあります
ProductId Name RegistrationDate UnregistrationDate
1 AB 2013-01-01 2013-03-01
2 CD 2013-01-10 2013-03-13
等
1年間の毎月の登録済み製品のリストを取得したいと考えています。
例 : 年 、 月 、および登録されていて未登録ではないディーラーの数。
Year Month RegisteredProucts
2013 2 35
2013 3 45(includes products even registered before March 2013)
次のストアド プロシージャを作成して、登録済みの製品を 1 か月間検索します。
@Begin Time = First Day of the Month
@End Time = Last Day of the Month
select COUNT(DISTINCT P.ProductId) as RegisteredProducts from Product P
where ((P.RegisteredDate < @EndTime)
AND (P.UnregisteredDate > @EndTime))
次に、以下のクエリを書きましたが、RegisteredDate で結果をグループ化しているようです。登録済みの製品 (未登録ではない) を 1 年間、毎月末までにグループ化する方法を教えてください。
select YEAR(P.RegisteredDate) AS [YEAR],MONTH(P.RegisteredDate) AS [MONTH], COUNT(DISTINCT P.ProductId) as RegisteredProducts from Product P
where ((P.RegisteredDate < @EndTime)
AND (P.UnregisteredDate > @EndTime))
group by YEAR(D.RegisteredDate), MONTH(D.RegisteredDate)