1

月単位で利用可能なオブジェクトの数を表示する棒グラフを作成したいと思います。すべての行には開始日と終了日があります。私は1か月のカウントを行う方法を知っています:

SELECT COUNT(*) As NumberOfItems
FROM Items
WHERE DATEPART(MONTH, Items.StartDate) <= @monthNumber 
AND DATEPART(MONTH, Items.EndDate) >= @monthNumber

次に、単一のSELECTステートメントを使用して月番号とアイテム数を取得するSQLを作成します。

これを達成するためのエレガントな方法はありますか?年番号を考慮に入れる必要があることは承知しています。

4

1 に答える 1

3

SqlServer2005以降を想定しています。

CTE部分は、@startDateと@endDateの間の年にまたがる月番号を返します。本体は、Items.StartDateとItems.EndDateで同じ変換を実行するアイテムと月番号を結合します。

; with months (month) as (
  select datediff (m, 0, @startDate)
  union all
  select month + 1
    from months
  where month < datediff (m, 0, @endDate)
)
select year (Items.StartDate) Year,
       month (Items.StartDate) Month,
       count (*) NumberOfItems
  from months
  inner join Items
     on datediff (m, 0, Items.StartDate) <= months.month
    and datediff (m, 0, Items.EndDate) >= months.month
  group by 
       year (Items.StartDate),
       month (Items.StartDate)

注:100か月を超える場合はoption (maxrecursion 0)、クエリの最後に必要になります。

于 2012-04-04T08:22:42.253 に答える