1

次のようなテーブルがあります。

Month          Value
2012-08-01      0.345
2012-09-01      0.543
2012-10-01      0.321
2012-11-01      0.234
2012-12-01      0.234

ユーザーは、「2012-09-29」から「2012-10-13」までの週の範囲を入力します 出力は、要求された範囲内のすべての週の結果と、次のロジックを使用した各週の平均値を表示する必要があります: - すべての平日が完全に 1 か月の場合、その月の月額値を使用します。平日が 2 か月にまたがっている場合は、その週の日数が最も多い月を優先して、2 か月間の平均として週額値を計算します。

誰かがT-SQLでこのようなことをする方法を私に教えてくれれば、それは非常に高く評価されます.

4

2 に答える 2

1

最後のクエリはその例です。カレンダー テーブルは要求に応じて構築されますが、すべてのデータベースは、代わりに日付範囲をフィルター処理する永続的なカレンダー テーブルを使用できます。

declare @tbl table (
  Month datetime,
  Value decimal(10,3));
insert @tbl select
'2012-08-01',      0.345 union all select
'2012-09-01',      0.543 union all select
'2012-10-01',      0.321 union all select
'2012-11-01',      0.234 union all select
'2012-12-01',      0.234;

declare @start datetime, @end datetime;
select @start = '2012-09-29', @end ='2012-10-13';

;with Calendar(TheDate,StartOfWeek,StartOfMonth) as(
  select @start, @start+1-Datepart(dw,@start), @start-Day(@start)+1
  union all
  select TheDate+1, TheDate+1+1-Datepart(dw,TheDate+1),
         TheDate+1-Day(TheDate+1)+1
  from Calendar
  where TheDate < @end
)
select case when @start > v.StartOfWeek
            then @start else v.StartOfWeek end RangeStart,
       case when @end < v.StartOfWeek+6
            then @end else v.StartOfWeek+6 end RangeEnd,
       cast(avg(m.value) as decimal(10,3)) [Average]
from Calendar v
join @tbl m on v.StartOfMonth = m.Month
group by v.StartOfWeek;

出力

RANGESTART          RANGEEND            Average
September, 29 2012  September, 29 2012  0.543
September, 30 2012  October, 06 2012    0.353
October, 07 2012    October, 13 2012    0.321
于 2012-10-18T16:53:04.313 に答える
1

あなたのクエリは次のようになります。アイデアは、翌月の最初の日を見つけることですDATEADD(mm, DATEDIFF(mm, 0, Month) + 1, 0 . 日数を計算すると、月の合計を取得し、それに基づいて平均を計算できます今月と翌月の最初の日との差 (SQL 構文のクリーンアップが必要な場合があります)。

declare @startdate datetime
declare  @enddate datetime

set @startdate = '2012-09-05'
set @enddate ='2012-10-13'

 Select Monthtotal/DateDiff(d,Month,NextMonth)
    FROM
        (Select 
         Month, DATEADD(mm, DATEDIFF(mm, 0, Month) + 1, 0) NextMonth, 
         DateDiff(d,Month, DATEADD(mm, DATEDIFF(mm, 0, Month) + 1, 0) * Value as Monthtotal
        FROM  DatesTable
        WHERE 
            @startdate >= Month and 
            @enddate <= DATEADD(mm, DATEDIFF(mm, 0, Month) + 1, 0)) 
于 2012-10-18T16:56:18.147 に答える